﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.Common;
using System.Collections.ObjectModel;
using FIFP.DashBoard.Model;
using Telerik.Windows.Controls;
using System.Collections.Generic;
using System.Linq;
using FIFP.DashBoard.Helper;
using System.ComponentModel;
using FIFP.DashBoard.Converters;
using FIFP.DashBoard.Views;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Linq.Expressions;
using System.Text.RegularExpressions;

namespace FIFP.DashBoard.ViewModel
{
    public class ShutdownMngVM : ViewModelCore, INotifyPropertyChanged, INotifyDataErrorInfo
    {
        #region Variables
        private List<FIFPAppointment> lsdActivities;
        private List<string> closedStringList = new List<string>();
        private List<FIFPAppointment> shutdownPlans;
        private ObservableCollection<FIFPAppointment> linkedShutdownList;
        private ObservableCollection<FIFPAppointment> filteredLinkedShutdownList;
        private string selectedClosedString;
        public event EventHandler<CustomEventArgs<AppointmentGroup>> OnAppointmentDataCompleted;

        private List<FIFPAppointment> activityListWithSelectedUnit;
        private ObservableCollection<FIFPAppointment> filteredActivityListWithSelectedUnit;
        PercentagePopup popup;
        ReducedCapacityPopup capacityPopup;
        private readonly ICollection<ValidationResult> _validationResults;
        private bool IsSIMOPS;
        #endregion

        #region Properties

        private ObservableCollection<Unit> filteredLSDLocations;
        public ObservableCollection<Unit> FilteredLSDLocations
        {
            get { return filteredLSDLocations; }
            set { SetPropertyValue(() => FilteredLSDLocations, value, val => filteredLSDLocations = val); }
        }

        private List<Unit> linkedShutdownLocations = new List<Unit>();
        public List<Unit> LinkedShutdownLocations
        {
            get { return linkedShutdownLocations; }
            set { SetPropertyValue(() => LinkedShutdownLocations, value, val => linkedShutdownLocations = val); }
        }

        private Unit selectedLSDLocation;
        public Unit SelectedLSDLocation
        {
            get { return selectedLSDLocation; }
            set { SetPropertyValue(() => SelectedLSDLocation, value, val => selectedLSDLocation = val); }
        }

        public List<FIFPAppointment> LsdActivities
        {
            get { return lsdActivities; }
            set { SetPropertyValue(() => LsdActivities, value, val => lsdActivities = val); }
        }

        public string SelectedClosedString
        {
            get { return selectedClosedString; }
            set
            {
                if (value == null)
                    return;
                selectedClosedString = value;
                OnPropertyChanged(() => SelectedClosedString);
            }
        }

        public List<string> ClosedStringList
        {
            get { return closedStringList; }
            set { SetPropertyValue(() => ClosedStringList, value, val => closedStringList = val); }
        }


        public ObservableCollection<FIFPAppointment> LinkedShutdownList
        {
            get { return linkedShutdownList; }
            set { SetPropertyValue(() => LinkedShutdownList, value, val => linkedShutdownList = val); }
        }

        public ObservableCollection<FIFPAppointment> FilteredLinkedShutdownList
        {
            get { return filteredLinkedShutdownList; }
            set { SetPropertyValue(() => FilteredLinkedShutdownList, value, val => filteredLinkedShutdownList = val); }
        }

        public List<FIFPAppointment> ShutdownPlans
        {
            get { return shutdownPlans; }
            set { SetPropertyValue(() => ShutdownPlans, value, val => shutdownPlans = val); }
        }

        private bool isCombinedTowerEnabled = false;
        public bool IsCombinedTowerEnabled
        {
            get { return isCombinedTowerEnabled; }
            set { SetPropertyValue(() => IsCombinedTowerEnabled, value, val => isCombinedTowerEnabled = val); }
        }

        private bool isApplySIMOPSEnabled = false;
        public bool IsApplySIMOPSEnabled
        {
            get { return isApplySIMOPSEnabled; }
            set { SetPropertyValue(() => IsApplySIMOPSEnabled, value, val => isApplySIMOPSEnabled = val); }
        }

        private bool isCancelSIMOPSEnabled = false;
        public bool IsCancelSIMOPSEnabled
        {
            get { return isCancelSIMOPSEnabled; }
            set { SetPropertyValue(() => IsCancelSIMOPSEnabled, value, val => isCancelSIMOPSEnabled = val); }
        }

        private bool isApplyCrossLineEnabled = false;
        public bool IsApplyCrossLineEnabled
        {
            get { return isApplyCrossLineEnabled; }
            set { SetPropertyValue(() => IsApplyCrossLineEnabled, value, val => isApplyCrossLineEnabled = val); }
        }

        private bool isCancelCrossLineEnabled = false;
        public bool IsCancelCrossLineEnabled
        {
            get { return isCancelCrossLineEnabled; }
            set { SetPropertyValue(() => IsCancelCrossLineEnabled, value, val => isCancelCrossLineEnabled = val); }
        }

        private bool isLSDRevertEnabled = false;
        public bool IsLSDRevertEnabled
        {
            get { return isLSDRevertEnabled; }
            set { SetPropertyValue(() => IsLSDRevertEnabled, value, val => isLSDRevertEnabled = val); }
        }

        private bool isBypassMOLEnabled = false;
        public bool IsBypassMOLEnabled
        {
            get { return isBypassMOLEnabled; }
            set { SetPropertyValue(() => IsBypassMOLEnabled, value, val => isBypassMOLEnabled = val); }
        }

        private FIFPAppointment selectedActivity;
        public FIFPAppointment SelectedActivity
        {
            get { return selectedActivity; }
            set { SetPropertyValue(() => SelectedActivity, value, val => selectedActivity = val); }
        }

        private FIFPAppointment modifiedSelectedActivity;
        public FIFPAppointment ModifiedSelectedActivity
        {
            get { return modifiedSelectedActivity; }
            set { SetPropertyValue(() => ModifiedSelectedActivity, value, val => modifiedSelectedActivity = val); }
        }

        public List<FIFPAppointment> ActivityListWithSelectedUnit
        {
            get { return activityListWithSelectedUnit; }
            set { SetPropertyValue(() => ActivityListWithSelectedUnit, value, val => activityListWithSelectedUnit = val); }
        }

        public ObservableCollection<FIFPAppointment> FilteredActivityListWithSelectedUnit
        {
            get { return filteredActivityListWithSelectedUnit; }
            set { SetPropertyValue(() => FilteredActivityListWithSelectedUnit, value, val => filteredActivityListWithSelectedUnit = val); }
        }
        private ObservableCollection<FIFPAppointment> modifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
        public ObservableCollection<FIFPAppointment> ModifiedLinkedShutdownList
        {
            get { return modifiedLinkedShutdownList; }
            set { SetPropertyValue(() => ModifiedLinkedShutdownList, value, val => modifiedLinkedShutdownList = val); }
        }


        private List<Unit> treeViewUnitList = new List<Unit>();
        public List<Unit> TreeViewUnitList
        {
            get { return treeViewUnitList; }
            set { SetPropertyValue(() => TreeViewUnitList, value, val => treeViewUnitList = val); }
        }

        private List<Unit> unitList = new List<Unit>();
        public List<Unit> UnitList
        {
            get { return unitList; }
            set { SetPropertyValue(() => UnitList, value, val => unitList = val); }
        }



        private string capacityPercentage = "100";
        [Display(Name = FIFPConstants.DISPLAY_PERCENTAGE)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_PERCENTAGE)]
        public string CapacityPercentage
        {
            get { return capacityPercentage; }
            set
            {
                if (CapacityPercentage != value)
                {
                    capacityPercentage = value;
                    OnPropertyChanged(() => this.capacityPercentage);
                }
            }
        }

        private string reducedUnitCapacity;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_REDUCEDCAPACITY)]
        public string ReducedUnitCapacity
        {
            get { return reducedUnitCapacity; }
            set
            {
                if (reducedUnitCapacity != value)
                {
                    reducedUnitCapacity = value;
                    OnPropertyChanged(() => this.reducedUnitCapacity);
                }
            }
        }

        private string rcUnitCapacity;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_REDUCEDCAPACITY1)]
        public string RcUnitCapacity
        {
            get { return rcUnitCapacity; }
            set
            {
                if (rcUnitCapacity != value)
                {
                    rcUnitCapacity = value;
                    OnPropertyChanged(() => this.rcUnitCapacity);
                }
            }
        }

        private double originalCapacity;
        public double OriginalCapacity
        {
            get { return originalCapacity; }
            set { SetPropertyValue(() => OriginalCapacity, value, val => originalCapacity = val); }
        }

        private string _UnitName = string.Empty;
        [Display(Name = FIFPConstants.DISPLAY_UNITNAME)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_UNITNAME)]
        public string UnitName
        {
            get { return _UnitName; }
            set
            {
                if (_UnitName != value)
                {
                    _UnitName = value;
                    OnPropertyChanged(() => this._UnitName);
                }
            }
        }

        private string _RCUnitName = string.Empty;
        public string RCUnitName
        {
            get { return _RCUnitName; }
            set
            {
                if (_RCUnitName != value)
                {
                    _RCUnitName = value;
                    OnPropertyChanged(() => this._RCUnitName);
                }
            }
        }


        private bool isUnitNameExist = false;
        public bool IsUnitNameExist
        {
            get { return isUnitNameExist; }
            set { SetPropertyValue(() => IsUnitNameExist, value, val => isUnitNameExist = val); }
        }

        private Grid treeViewGrid;
        public Grid TreeViewGrid
        {
            get { return treeViewGrid; }
            set { SetPropertyValue(() => TreeViewGrid, value, val => treeViewGrid = val); }
        }

        private bool isEnabledRaducedCapacity = false;
        public bool IsEnabledRaducedCapacity
        {
            get { return isEnabledRaducedCapacity; }
            set { SetPropertyValue(() => IsEnabledRaducedCapacity, value, val => isEnabledRaducedCapacity = val); }
        }

        private Unit selectedTreeViewUnit;
        public Unit SelectedTreeViewUnit
        {
            get { return selectedTreeViewUnit; }
            set { SetPropertyValue(() => SelectedTreeViewUnit, value, val => selectedTreeViewUnit = val); }
        }

        private DataGrid modifiedDataGrid;
        public DataGrid ModifiedDataGrid
        {
            get { return modifiedDataGrid; }
            set { SetPropertyValue(() => ModifiedDataGrid, value, val => modifiedDataGrid = val); }
        }

        private DataGrid activitiesDataGrid;
        public DataGrid ActivitiesDataGrid
        {
            get { return activitiesDataGrid; }
            set { SetPropertyValue(() => ActivitiesDataGrid, value, val => activitiesDataGrid = val); }
        }


        private Unit upperLevelUnit;
        public Unit UpperLevelUnit
        {
            get { return upperLevelUnit; }
            set { SetPropertyValue(() => UpperLevelUnit, value, val => upperLevelUnit = val); }
        }
        private List<ReducedCapacity> reducedCapacityList = new List<ReducedCapacity>();
        public List<ReducedCapacity> ReducedCapacityList
        {
            get { return reducedCapacityList; }
            set { SetPropertyValue(() => ReducedCapacityList, value, val => reducedCapacityList = val); }
        }

        private List<ReducedCapacity> reducedCapacityBindList = new List<ReducedCapacity>();
        public List<ReducedCapacity> ReducedCapacityBindList
        {
            get { return reducedCapacityBindList; }
            set { SetPropertyValue(() => ReducedCapacityBindList, value, val => reducedCapacityBindList = val); }
        }

        private List<int> occpRadialUnitIds = new List<int>();
        public List<int> OccpRadialUnitIds
        {
            get { return occpRadialUnitIds; }
            set { SetPropertyValue(() => OccpRadialUnitIds, value, val => occpRadialUnitIds = val); }
        }

        private bool isNodeExists = false;
        public bool IsNodeExists
        {
            get { return isNodeExists; }
            set { SetPropertyValue(() => IsNodeExists, value, val => isNodeExists = val); }
        }

        private bool isRCReversed = false;
        public bool IsRCReversed
        {
            get { return isRCReversed; }
            set { SetPropertyValue(() => IsRCReversed, value, val => isRCReversed = val); }
        }

        private List<FIFPAppointment> scheduleViewAppointments = new List<FIFPAppointment>();
        public List<FIFPAppointment> ScheduleViewAppointments
        {
            get { return scheduleViewAppointments; }
            set { SetPropertyValue(() => ScheduleViewAppointments, value, val => scheduleViewAppointments = val); }
        }

        #endregion

        #region Commands
        private ICommand _ClosedStringSelectionCommand;
        public ICommand ClosedStringSelectionCommand
        {
            get
            {
                return _ClosedStringSelectionCommand ??
                        (_ClosedStringSelectionCommand = new RelayCommand<ComboBox>(ClosedStringFilter));
            }
        }

        private ICommand _ActivitySelectChanged;
        public ICommand ActivitySelectChanged
        {
            get
            {
                return _ActivitySelectChanged ??
                        (_ActivitySelectChanged = new RelayCommand<DataGrid>(ActivityDatagridSelectionChange));
            }
        }

        private ICommand _ModifiedActivitySelectChanged;
        public ICommand ModifiedActivitySelectChanged
        {
            get
            {
                return _ModifiedActivitySelectChanged ??
                        (_ModifiedActivitySelectChanged = new RelayCommand<DataGrid>(ModifiedActivityDatagridSelectionChange));
            }
        }


        private ICommand _SIMOPSClickCommand;
        public ICommand SIMOPSClickCommand
        {
            get
            {
                return _SIMOPSClickCommand ??
                        (_SIMOPSClickCommand = new RelayCommand<Button>(ReloadTimelineViewBySIMOPS));
            }
        }

        private ICommand _CrossingLineClickCommand;
        public ICommand CrossingLineClickCommand
        {
            get
            {
                return _CrossingLineClickCommand ??
                        (_CrossingLineClickCommand = new RelayCommand<Button>(ReloadTimelineViewByCrossingLine));
            }
        }

        private ICommand _LSDLocationSelectionChanged;
        public ICommand LSDLocationSelectionChanged
        {
            get
            {
                return _LSDLocationSelectionChanged ??
                        (_LSDLocationSelectionChanged = new RelayCommand<DataGrid>(LSDLocationGridSelectionChange));
            }
        }
        private ICommand _CancelCommand;
        public ICommand CancelCommand
        {
            get { return _CancelCommand ?? (_CancelCommand = new RelayCommand<Button>(HidePopup)); }
        }
        private ICommand _WarningCommand;
        public ICommand WarningCommand
        {
            get
            {
                return _WarningCommand ??
                        (_WarningCommand = new RelayCommand<Button>(ShowPopup));
            }
        }



        private ICommand _ReducedCapacityPopupCommand;
        public ICommand ReducedCapacityPopupCommand
        {
            get
            {
                return _ReducedCapacityPopupCommand ??
                        (_ReducedCapacityPopupCommand = new RelayCommand<Button>(ReduceUnitCapacity));
            }
        }

        private ICommand _RCTextBoxCommand;
        public ICommand RCTextBoxCommand
        {
            get
            {
                return _RCTextBoxCommand ??
                        (_RCTextBoxCommand = new RelayCommand<object>(ReduceUnitCapacityKeyDown));
            }
        }

        private ICommand _PercentageTextBoxEnterKeyCommand;
        public ICommand PercentageTextBoxEnterKeyCommand
        {
            get
            {
                return _PercentageTextBoxEnterKeyCommand ??
                        (_PercentageTextBoxEnterKeyCommand = new RelayCommand<object>(PercentageByEnterKey));
            }
        }

        private ICommand _PercentageTextBoxLoadCommand;
        public ICommand PercentageTextBoxLoadCommand
        {
            get
            {
                return _PercentageTextBoxLoadCommand ??
                        (_PercentageTextBoxLoadCommand = new RelayCommand<TextBox>(LoadPercentageTextbox));
            }
        }


        private ICommand _RCTextBoxLoadCommand;
        public ICommand RCTextBoxLoadCommand
        {
            get
            {
                return _RCTextBoxLoadCommand ??
                        (_RCTextBoxLoadCommand = new RelayCommand<TextBox>(LoadRCTextBox));
            }
        }

        private ICommand _UnitNameSearchCommand;
        public ICommand UnitNameSearchCommand
        {
            get
            {
                return _UnitNameSearchCommand ??
                        (_UnitNameSearchCommand = new RelayCommand<object>(SearchByUnitName));
            }
        }

        private ICommand _TextBoxLoadCommand;
        public ICommand TextBoxLoadCommand
        {
            get
            {
                return _TextBoxLoadCommand ??
                        (_TextBoxLoadCommand = new RelayCommand<TextBox>(LoadTextBox));
            }
        }

        private ICommand _ReducedCapacityCommand;
        public ICommand ReducedCapacityCommand
        {
            get
            {
                return _ReducedCapacityCommand ??
                        (_ReducedCapacityCommand = new RelayCommand<object>(CalculateReducedCapacity));
            }
        }

        private ICommand _CencelSIMOPSEvent;
        public ICommand CencelSIMOPSEvent
        {
            get
            {
                return _CencelSIMOPSEvent ??
                        (_CencelSIMOPSEvent = new RelayCommand<Button>(CancelSIMOPS));
            }
        }

        private ICommand _CencelCrossingEvent;
        public ICommand CencelCrossingEvent
        {
            get
            {
                return _CencelCrossingEvent ??
                        (_CencelCrossingEvent = new RelayCommand<Button>(CancelCrossingLine));
            }
        }
        private ICommand _TreeviewGridLoaded;
        public ICommand TreeviewGridLoaded
        {
            get
            {
                return _TreeviewGridLoaded ??
                        (_TreeviewGridLoaded = new RelayCommand<Grid>(LoadTreeviewGrid));
            }
        }

        private ICommand _LSDRevertEnabledEvent;
        public ICommand LSDRevertEnabledEvent
        {
            get
            {
                return _LSDRevertEnabledEvent ??
                        (_LSDRevertEnabledEvent = new RelayCommand<Button>(RevertSDUnitToGanttChart));
            }
        }

        private ICommand _BypassMOLEvent;
        public ICommand BypassMOLEvent
        {
            get
            {
                return _BypassMOLEvent ??
                        (_BypassMOLEvent = new RelayCommand<Button>(BypassToMOL));
            }
        }

        #endregion

        #region Constructor
        public ShutdownMngVM()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                _validationResults = new List<ValidationResult>();
                filteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
                ServiceLocator.Get<MainPageVM>().OnLinkedShutdownClick += new EventHandler(ShutdownMngVM_OnLinkedShutdownClick);
                ServiceLocator.Get<FilterVM>().OnCombinedTowerClick += new EventHandler(ShutdownMngVM_OnCombinedTowerClick);
                LoadCombo();

            }
        }


        void ShutdownMngVM_OnCombinedTowerClick(object sender, EventArgs e)
        {
            if (ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked)
            {
                FilteredLSDLocations = new ObservableCollection<Unit>(from item in LinkedShutdownLocations
                                                                      where item.FluidType == FIFPConstants.FLUIDTYPE_COMBINED
                                                                      select item);
            }
            else
            {
                FilteredLSDLocations = new ObservableCollection<Unit>(LinkedShutdownLocations);
            }
            FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>();
        }
        #endregion

        #region Reset
        public void Reset()
        {
            LinkedShutdownLocations = new List<Unit>();
            FilteredLSDLocations = new ObservableCollection<Unit>();
            FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>();
            ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
            SelectedActivity = ModifiedSelectedActivity = null;
            if (TreeViewGrid != null && TreeViewGrid.Children.Count > 0)
                TreeViewGrid.Children.Clear();
        }

        public void ResetFromFilter()
        {
            FilteredLSDLocations = new ObservableCollection<Unit>();
            FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>();
            ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
            SelectedActivity = ModifiedSelectedActivity = null;
            if (TreeViewGrid != null && TreeViewGrid.Children.Count > 0)
                TreeViewGrid.Children.Clear();
        }

        #endregion

        #region Get the original plans from Import UI while we click linked shutdown button from MainPage
        void ShutdownMngVM_OnLinkedShutdownClick(object sender, EventArgs e)
        {
            //LoadUnitTypeFacilityList();
            //ServiceLocator.Get<FilterVM>().IsDivisionEnabled = false;
            ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked = false;
            IsApplySIMOPSEnabled = IsApplyCrossLineEnabled = IsCancelSIMOPSEnabled = IsCancelCrossLineEnabled = false;
            LinkedShutdownLocations = new List<Unit>(); //Retailn the previous state
            IsCombinedTowerEnabled = false;
            SelectedClosedString = FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS;
            ServiceLocator.Get<AppointmentVM>().RadScheduleViewDragDropBehavior = new ScheduleDragDropBehavior();
            ShutdownPlans = ServiceLocator.Get<ImportVM>().ImportPlans.OrderBy(s => s.nIndex).ToList<FIFPAppointment>();
            //ShutdownPlans = (from item in ServiceLocator.Get<ImportVM>().ScenarioPlans
            //                 where (item.Start >= ServiceLocator.Get<FilterVM>().StartDate && item.End <= ServiceLocator.Get<FilterVM>().EndDate)
            //                 orderby item.nIndex ascending
            //                 select item).ToList<FIFPAppointment>();
            if (ShutdownPlans.Count == 0) //If there is no plans, then reset the previous state.
                Reset();
            ShutdownPlans.ForEach(s => { s.ActivityLevel = 1; });//Undo only page level
            UnitList = ServiceLocator.Get<ImportVM>().UnitList;
            ReducedCapacityBindList = ServiceLocator.Get<ImportVM>().ReducedCapacityList;
            GetOCCPRadialUnits();

            //if (LinkedShutdownLocations.Count == 0)
            {
                foreach (Unit unit in UnitList)
                {
                    unit.UnitNameTextColor = (unit.FluidType == FIFPConstants.FLUIDTYPE_OIL) ? new SolidColorBrush(new Color() { R = 0xFF, G = 0x59, B = 0x59, A = 0xFF }) : (unit.FluidType == FIFPConstants.FLUIDTYPE_WATER) ? new SolidColorBrush(new Color() { R = 0x4B, G = 0xAC, B = 0xC6, A = 0xFF }) : (unit.FluidType == FIFPConstants.FLUIDTYPE_GAS) ? new SolidColorBrush(new Color() { R = 0x93, G = 0xA8, B = 0x2A, A = 0xFF }) : (unit.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD) ? new SolidColorBrush(new Color() { R = 0x2E, G = 0x2E, B = 0x2E, A = 0xFF }) : new SolidColorBrush(new Color() { R = 0x91, G = 0x00, B = 0xe5, A = 0xFF });
                }

                if (ShutdownPlans != null && ShutdownPlans.Count > 0)
                {
                    foreach (FIFPAppointment activity in ShutdownPlans)
                    {
                        //Filter lsd plans according to the selection of selected location fluid type and it is applicable for pipelines and radials
                        if ((activity.UnitName != FIFPConstants.UNITTYPE_MOL && activity.UnitName != FIFPConstants.UNITTYPE_BYPASS_MOL && activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE) || activity.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                        {
                            if (activity.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                                activity.LsdPlans = activity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<FIFPAppointment>();
                            else if (activity.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                                activity.LsdPlans = activity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<FIFPAppointment>();
                            else if (activity.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                                activity.LsdPlans = activity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<FIFPAppointment>();
                        }
                        activity.LsdPlans.ForEach(s => { s.IsAppointmentDelete = true; });//We set to true that delete linked shutdown activity in LSD page
                        if (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && activity.UnitName == FIFPConstants.UNITTYPE_MOL)
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => (l.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || (l.UnitType == FIFPConstants.UNITTYPE_PIPELINE && l.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL) && l.IsLinkedShutdownPlan == true)));
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && activity.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_RADIAL && l.IsLinkedShutdownPlan == true)));
                            foreach (FIFPAppointment appointment in activity.LsdPlans.Where(s => s.IsRadialSwitch == false))
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM && activity.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM)
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => (l.UnitName == FIFPConstants.PLATFORM_ERP_UNIT || l.UnitName == FIFPConstants.PLATFORM_NRP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT) && l.IsLinkedShutdownPlan == true));
                            foreach (FIFPAppointment appointment in activity.LsdPlans.Where(s => s.IsRadialSwitch == false))
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM && (activity.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || activity.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT))
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_SEPERATOR && l.IsLinkedShutdownPlan == true));
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM && activity.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR || l.UnitType == FIFPConstants.UNITTYPE_TOWER) && l.IsLinkedShutdownPlan == true));
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                        {
                            activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_RADIAL || l.UnitType == FIFPConstants.UNITTYPE_MODULE) && l.IsLinkedShutdownPlan == true));
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_RADIAL || (activity.UnitType == FIFPConstants.UNITTYPE_TOWER && activity.FluidType != FIFPConstants.FLUIDTYPE_COMBINED) || (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && (activity.UnitName != FIFPConstants.UNITTYPE_MOL && activity.UnitName != FIFPConstants.UNITTYPE_BYPASS_MOL)))
                        {
                            if (activity.IsAppliedLSDSimops)
                            {
                                activity.LsdReason = "SIMOPS applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedLSDSimops = true;
                            }
                            if (activity.IsAppliedCrossingLine)
                            {
                                activity.LsdReason = "Crossing line applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedCrossingLine = true;
                            }
                            if (activity.IsAppliedCrossingLine || activity.IsAppliedLSDSimops)
                                activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == false));
                            else
                                activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_TOWER && activity.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                        {
                            if (activity.IsAppliedLSDSimops)
                            {
                                activity.LsdReason = "SIMOPS applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedLSDSimops = true;
                            }
                            if (activity.IsAppliedCrossingLine)
                            {
                                activity.LsdReason = "Crossing line applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedCrossingLine = true;
                            }
                            if (activity.FilteredLsdPlans.Count == 0) //Combined tower has only one linked shutdown which is Water tower. Then from closed string drop down user choose oil strings then we remove water from scheduleview. Then user go to import page and come back LSD then we don't have any linked shutdown in turn we are not shown UT-81 in Linked shutdown location.
                            {
                                if (activity.IsAppliedCrossingLine || activity.IsAppliedLSDSimops)
                                    activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == false));
                                else
                                    activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                            }
                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                        }
                        else if (activity.UnitType == FIFPConstants.UNITTYPE_WELL && (activity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || activity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))
                        {
                            if (activity.IsAppliedCrossingLine || activity.IsAppliedLSDSimops)
                                activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == false));
                            else
                                activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                            if (activity.IsAppliedLSDSimops)
                            {
                                activity.LsdReason = "SIMOPS applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedLSDSimops = true;
                            }
                            if (activity.IsAppliedCrossingLine)
                            {
                                activity.LsdReason = "Crossing line applied";
                                foreach (FIFPAppointment appoinment in activity.LsdPlans.Where(s => activity.LSDDeletedIds.Any(a => a.Equals(activity.UnitID))))
                                    appoinment.IsAppliedCrossingLine = true;
                            }

                            foreach (FIFPAppointment appointment in activity.LsdPlans)
                            {
                                appointment.Start = activity.Start; appointment.End = activity.End; appointment.ParentActivityCode = activity.ActivityCode;
                            }
                            Unit wellUnit = UnitList.Where(u => u.UnitName == activity.UnitName && u.UnitType == activity.UnitType).FirstOrDefault();
                            if (wellUnit != null && !LinkedShutdownLocations.Contains(wellUnit) && activity.FilteredLsdPlans.Count > 0)
                            {
                                LinkedShutdownLocations.Add(wellUnit);
                            }

                        }
                        Unit unit = UnitList.Where(u => u.UnitName == activity.UnitName && u.UnitType == activity.UnitType).FirstOrDefault();
                        if (unit != null && unit.UnitType != FIFPConstants.UNITTYPE_STRING && unit.UnitType != FIFPConstants.UNITTYPE_WELL && !LinkedShutdownLocations.Contains(unit) && activity.FilteredLsdPlans.Count > 0)
                        {
                            LinkedShutdownLocations.Add(unit);
                        }
                        else if (!LinkedShutdownLocations.Contains(unit) && activity.IsAppliedLSDSimops || activity.IsAppliedCrossingLine)
                            LinkedShutdownLocations.Add(unit);

                        //if (activity.UnitType == FIFPConstants.UNITTYPE_TOWER && activity.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                        //    LinkedShutdownLocations.Add(unit);

                    }
                    if (LinkedShutdownLocations.Count > 0)
                    {
                        //FilteredLSDLocations = new ObservableCollection<Unit>(LinkedShutdownLocations);
                        ServiceLocator.Get<FilterVM>().FilterAppoinements(false);
                    }
                }
            }
            //else
            //{
            //    ServiceLocator.Get<FilterVM>().FilterAppoinements();
            //}
            List<FIFPAppointment> listForScheduleView = new List<FIFPAppointment>();
            if (FilteredLinkedShutdownList != null && FilteredLinkedShutdownList.Count > 0 && SelectedActivity != null && !FilteredLinkedShutdownList.Contains(SelectedActivity))
                listForScheduleView.Add(SelectedActivity);
            listForScheduleView.AddRange(FilteredLinkedShutdownList);
            LoadTimelineView(listForScheduleView);
        }

        private void LoadUnitTypeFacilityList()
        {
            List<FilterData> unitTypeList = new List<FilterData>(ServiceLocator.Get<FilterVM>().UnitTypeList);
            unitTypeList.ForEach(s => { s.ItemVisibility = (s.FilterTypeName == FIFPConstants.UNITTYPE_STRING) ? Visibility.Collapsed : Visibility.Visible; });
            ServiceLocator.Get<FilterVM>().UnitTypeList = new ObservableCollection<FilterData>(unitTypeList);

            List<FilterData> facilityList = new List<FilterData>(ServiceLocator.Get<FilterVM>().FacilityList);
            facilityList.ForEach(s => { s.ItemVisibility = (s.FilterTypeName == FIFPConstants.UNITTYPE_PLATFORM) ? Visibility.Visible : Visibility.Collapsed; });
            ServiceLocator.Get<FilterVM>().FacilityList = new ObservableCollection<FilterData>(facilityList);
        }

        private void MakeCombinedTowerChildUnits(List<Unit> LinkedShutdownLocations)
        {
            foreach (Unit selectedUnit in LinkedShutdownLocations)
            {
                if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_TOWER && selectedUnit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                {
                    List<Unit> childUnits = UnitList.Where(s => s.UnitName == selectedUnit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                    if (selectedUnit != null)
                        selectedUnit.ChildUnitList = childUnits;
                }
            }
        }

        private void GetOCCPRadialUnits()
        {
            if (OccpRadialUnitIds.Count > 0)
                OccpRadialUnitIds.AddRange(UnitList.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).SelectMany(p => p.ChildUnitList).Select(m => m.UnitID).ToList<int>());
            else
                OccpRadialUnitIds = UnitList.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).SelectMany(p => p.ChildUnitList).Select(m => m.UnitID).ToList<int>();
        }
        #endregion

        #region Load data to Combined towers combo
        private void LoadCombo()
        {
            ClosedStringList = new List<string>() { FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS, FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS, FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS };
            SelectedClosedString = ClosedStringList[0];
        }
        #endregion

        #region Closed String combo filter
        private void ClosedStringFilter(ComboBox cmbFilter)
        {
            if (!string.IsNullOrEmpty(SelectedClosedString) && SelectedActivity != null)
            {
                SelectedActivity.SelectedOilString = SelectedClosedString;
                SelectedActivity.IsModified = SelectedActivity.IsModified == 1 ? 1 : 0;
                List<FIFPAppointment> listForScheduleView = new List<FIFPAppointment>();
                foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
                {
                    listForScheduleView.Add(appointment);


                    if (appointment == SelectedActivity)
                    {
                        switch (SelectedClosedString)
                        {
                            case FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS:
                                listForScheduleView.AddRange((from item in appointment.FilteredLsdPlans
                                                              where (item.FluidType == FIFPConstants.FLUIDTYPE_WATER || item.FluidType == FIFPConstants.FLUIDTYPE_OIL || item.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                                                              select item).ToList<FIFPAppointment>());

                                SelectedActivity.LsdPlans.ForEach(s => { s.IsLinkedShutdownPlan = true; s.SelectedString = SelectedClosedString; });//Selected activity contains default unit shutdown strings
                                break;
                            case FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS:
                                listForScheduleView.AddRange((from item in appointment.FilteredLsdPlans
                                                              where item.FluidType == FIFPConstants.FLUIDTYPE_OIL || item.FluidType == FIFPConstants.FLUIDTYPE_COMBINED
                                                              select item).ToList<FIFPAppointment>());

                                SelectedActivity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = true; });
                                SelectedActivity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
                                break;
                            case FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS:
                                listForScheduleView.AddRange((from item in appointment.FilteredLsdPlans
                                                              where item.FluidType == FIFPConstants.FLUIDTYPE_WATER || item.FluidType == FIFPConstants.FLUIDTYPE_COMBINED
                                                              select item).ToList<FIFPAppointment>());
                                SelectedActivity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = true; });
                                SelectedActivity.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
                                break;
                        }
                    }
                    else
                        listForScheduleView.AddRange(appointment.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));
                }
                listForScheduleView.ForEach(s => { s.SelectedString = SelectedClosedString; });
                LoadTimelineView(listForScheduleView);
            }
        }
        #endregion

        #region Undo
        public void UndoLSDActivities()
        {
            if (ScheduleViewAppointments != null && ScheduleViewAppointments.Count > 0 && ScheduleViewAppointments.Where(s => s.ActivityLevel > 1).Count() > 0)
            {
                foreach (FIFPAppointment appointment in ScheduleViewAppointments.Where(s => s.ActivityLevel > 1))
                {
                    appointment.Start = appointment.ModifiedStart;
                    appointment.End = appointment.ModifiedEnd;
                    ResetUndoActivity(appointment);
                }
                LoadTimelineView(ScheduleViewAppointments);
            }
        }

        private void ResetUndoActivity(FIFPAppointment appointment)
        {
            ServiceLocator.Get<AppointmentVM>().SynchronizeRC(appointment);
            foreach (FIFPAppointment activity in ActivityListWithSelectedUnit)
            {
                if (appointment.Equals(activity))
                {
                    foreach (FIFPAppointment lsdPlan in activity.LsdPlans) //update modified date to lsd plans
                    {
                        lsdPlan.Start = appointment.Start;
                        lsdPlan.End = appointment.End;
                    }
                    foreach (FIFPAppointment lsdPlan in activity.FilteredLsdPlans) //update modified date to filtered plans
                    {
                        lsdPlan.Start = appointment.Start;
                        lsdPlan.End = appointment.End;
                    }
                    foreach (FIFPAppointment lsdPlan in ModifiedLinkedShutdownList) //update modified date to modified plans
                    {
                        lsdPlan.Start = appointment.Start;
                        lsdPlan.End = appointment.End;
                    }
                    break;
                }
            }
        }
        #endregion

        #region LoadTimelineView
        public void LoadTimelineView(List<FIFPAppointment> plans)
        {
            ScheduleViewAppointments = plans;
            AppointmentGroup appointmentGroup = new AppointmentGroup();
            List<ResourceType> lstResources = new List<ResourceType>();
            List<Resource> unitList = new List<Resource>();
            ResourceType unitType = new ResourceType("Unit");
            unitType.DisplayName = "Unit";
            unitType.Name = "Unit";

            foreach (FIFPAppointment appointment in plans)
            {
                if (appointment != null)
                {
                    Resource resource = new Resource() { ResourceName = appointment.UnitName, DisplayName = appointment.UnitName, ResourceType = unitType.Name };
                    if (!unitList.Contains(resource))
                        unitList.Add(resource);
                    appointment.Resources.Add(resource);

                    if (appointment.PlanID > 0 && !string.IsNullOrEmpty(appointment.FluidType) && !appointment.IsLinkedShutdownPlan)
                    {
                        switch (appointment.FluidType)
                        {
                            case FIFPConstants.FLUIDTYPE_OIL:
                                appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Oil", new SolidColorBrush(new Color() { R = 0xFF, G = 0x59, B = 0x59, A = 0xFF }));
                                break;
                            case FIFPConstants.FLUIDTYPE_COMBINED:
                                appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Combined", new SolidColorBrush(new Color() { R = 0x80, G = 0x0D, B = 0x54, A = 0xFF }));
                                break;
                            case FIFPConstants.FLUIDTYPE_WATER:
                                appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Water", new SolidColorBrush(new Color() { R = 0x4B, G = 0xAC, B = 0xC6, A = 0xFF }));
                                break;
                            case FIFPConstants.FLUIDTYPE_GAS:
                                appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Gas", new SolidColorBrush(new Color() { R = 0x93, G = 0xA8, B = 0x2A, A = 0xFF }));
                                break;
                            case FIFPConstants.TOWERTYPE_MANIFOLD:
                                appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Manifold", new SolidColorBrush(new Color() { R = 0x2E, G = 0x2E, B = 0x2E, A = 0xFF }));
                                break;
                            default:
                                break;
                        }
                    }
                    if (appointment.IsLinkedShutdownPlan)
                        appointment.Category = null;

                }
            }

            appointmentGroup.Appointments = new List<FIFPAppointment>(plans);
            unitType.Resources.AddRange(unitList);
            lstResources.Add(unitType);


            appointmentGroup.ResourceTypes = lstResources;
            appointmentGroup.UnitList = unitList;

            if (OnAppointmentDataCompleted != null)
                OnAppointmentDataCompleted(this, new CustomEventArgs<AppointmentGroup>(appointmentGroup));

        }
        #endregion

        #region ActivityDatagridSelectionChange
        private void ActivityDatagridSelectionChange(DataGrid activityGrid)
        {
            if (activityGrid != null)
                ActivitiesDataGrid = activityGrid;
            FIFPAppointment activity = (FIFPAppointment)activityGrid.SelectedItem;
            if (activity != null)
            {
                //Get the deleted id list from database and assign the remarks and move it to modified activities grid
                List<FIFPAppointment> lstDeletedLSDs = GetDeletedLSDIdsFromDB(activity);
                //lstDeletedLSDs.ForEach(s => { s.LsdReason = "LSD deleted"; s.ActivityCode = "LSD"; });//Time being i commented out.Recheck later
                ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lstDeletedLSDs.Where(s => s.LsdReason != null)); //This LsdReason null check is for when the user choose combined tower closed string
                ModifiedLinkedShutdownList.AddRange((from item in ActivityListWithSelectedUnit
                                                     where item.UnitName == SelectedLSDLocation.UnitName && (item.IsAppliedCrossingLine || item.IsAppliedLSDSimops)
                                                     select item));



                IsCancelSIMOPSEnabled = IsCancelCrossLineEnabled = false;
                //If the unit type = tower then we enable apply simops and crossed line buttons
                if (activity.FilteredLsdPlans.Count > 0 && (activity.UnitType == FIFPConstants.UNITTYPE_TOWER && SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER) || (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && (activity.UnitType == FIFPConstants.UNITTYPE_WELL && activity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || activity.UnitType == FIFPConstants.UNITTYPE_WELL && activity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)))
                    IsApplySIMOPSEnabled = IsApplyCrossLineEnabled = true;
                else
                    IsApplySIMOPSEnabled = IsApplyCrossLineEnabled = false;

                //Apply reduced capacity for 
                //if (SelectedTreeViewUnit != null)//For Tower activities we can apply SIMOPS and Crossing line. We can't enter reduced capcity for tower activities.
                //    IsEnabledRaducedCapacity = true;
                //else
                //    IsEnabledRaducedCapacity = false;
                EnableReducedCapacity(activity);


                //Assign activity object to Property 
                SelectedActivity = activity;

                //If it is combined tower activity then assign the previously selected string from database.
                if (activity.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || activity.UnitName == FIFPConstants.TOWER_UT_22A || activity.UnitName == FIFPConstants.TOWER_UT_12A || activity.UnitName == FIFPConstants.TOWER_UT_40)
                {
                    SelectedClosedString = activity.SelectedOilString == string.Empty ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS : activity.SelectedOilString;
                    IsCombinedTowerEnabled = true;
                }
                else
                    IsCombinedTowerEnabled = false;
            }
        }

        private void EnableReducedCapacity(FIFPAppointment activity)
        {
            if (activity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || activity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST)
            {
                if (IsApplicableForRCBySelectedActivity(activity))
                {
                    IsEnabledRaducedCapacity = true;
                    RCUnitName = activity.UnitName;
                    Unit unit = UnitList.Where(s => s.UnitID == activity.UnitID).FirstOrDefault();
                    if (unit != null)
                        OriginalCapacity = unit.Capacity;

                    ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == unit.UnitID && s.PlanId == activity.PlanID && s.ParentUnitId == activity.UnitID && s.StartDate == activity.Start && s.EndDate == activity.End).FirstOrDefault();
                    if (rc != null)
                        ReducedUnitCapacity = Convert.ToString(rc.ReducedUnitCapacity);
                    else
                        ReducedUnitCapacity = "0";
                }
                else
                    IsEnabledRaducedCapacity = false;

                List<ReducedCapacity> rcList = (from item in ReducedCapacityBindList
                                                where item.ParentUnitId == activity.UnitID && item.PlanId == activity.PlanID && item.StartDate == activity.Start && item.EndDate == activity.End
                                                select item).ToList<ReducedCapacity>();
                if (rcList != null && rcList.Count > 0)
                {
                    foreach (ReducedCapacity capacity in rcList)
                    {
                        FIFPAppointment appointment = new FIFPAppointment() { UnitID = capacity.UnitId, LSDRCParentUnitId = activity.UnitID, PlanID = activity.PlanID, UnitName = activity.UnitName, Start = capacity.StartDate, End = capacity.EndDate, LsdReason = "Capacity reduced", ActivityCode = activity.ActivityCode };
                        ModifiedLinkedShutdownList.Add(appointment);
                    }
                }
            }
            else
            {
                if (SelectedTreeViewUnit != null && (activity.ActivityCode != FIFPConstants.ACTIVITY_CODE_TPC && activity.ActivityCode != FIFPConstants.ACTIVITY_CODE_CNST))
                {
                    IsEnabledRaducedCapacity = true;
                    RCUnitName = SelectedTreeViewUnit.UnitName;
                    Unit unit = UnitList.Where(s => s.UnitID == SelectedTreeViewUnit.UnitID).FirstOrDefault();
                    if (unit != null)
                        OriginalCapacity = unit.Capacity;

                    ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == unit.UnitID && s.PlanId == activity.PlanID && s.ParentUnitId == activity.UnitID && s.StartDate == activity.Start && s.EndDate == activity.End).FirstOrDefault();
                    if (rc != null)
                        ReducedUnitCapacity = Convert.ToString(rc.ReducedUnitCapacity);
                    else
                        ReducedUnitCapacity = "0";
                }
                else
                    IsEnabledRaducedCapacity = false;

                List<ReducedCapacity> rcList = (from item in ReducedCapacityBindList
                                                where item.ParentUnitId == activity.UnitID && item.PlanId == activity.PlanID && item.StartDate == activity.Start && item.EndDate == activity.End
                                                select item).ToList<ReducedCapacity>();
                if (rcList != null && rcList.Count > 0)
                {
                    foreach (ReducedCapacity capacity in rcList)
                    {
                        FIFPAppointment appointment = new FIFPAppointment() { UnitID = capacity.UnitId, PlanID = activity.PlanID, UnitName = activity.UnitName, Start = capacity.StartDate, End = capacity.EndDate, LsdReason = "Capacity reduced", ActivityCode = activity.ActivityCode };
                        ModifiedLinkedShutdownList.Add(appointment);
                    }
                }
            }
        }

        private List<FIFPAppointment> GetDeletedLSDIdsFromDB(FIFPAppointment activity)
        {
            List<FIFPAppointment> lstDeletedLSDs = new List<FIFPAppointment>();
            if (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && activity.UnitName == FIFPConstants.UNITTYPE_MOL)
                lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || (l.UnitType == FIFPConstants.UNITTYPE_PIPELINE && l.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL) && l.IsLinkedShutdownPlan == false)).ToList<FIFPAppointment>();
            else if (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && activity.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_RADIAL && l.IsLinkedShutdownPlan == false)).ToList<FIFPAppointment>();
            else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM && activity.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM)
            {
                lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitName == FIFPConstants.PLATFORM_ERP_UNIT || l.UnitName == FIFPConstants.PLATFORM_NRP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT || l.UnitType == FIFPConstants.UNITTYPE_RADIAL) && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
                //lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitName == FIFPConstants.PLATFORM_ERP_UNIT || l.UnitName == FIFPConstants.PLATFORM_NRP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT || OccpRadialUnitIds.Any(s => s.Equals(l.UnitID))) && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
            }
            else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM && (activity.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || activity.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT))
                lstDeletedLSDs = activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_SEPERATOR && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PLATFORM && SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)
                lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR || l.UnitType == FIFPConstants.UNITTYPE_TOWER) && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
            else if (activity.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                lstDeletedLSDs = activity.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_RADIAL || l.UnitType == FIFPConstants.UNITTYPE_MODULE) && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
            else if (activity.UnitType == FIFPConstants.UNITTYPE_RADIAL || activity.UnitType == FIFPConstants.UNITTYPE_TOWER || (activity.UnitType == FIFPConstants.UNITTYPE_TOWER && activity.FluidType == FIFPConstants.FLUIDTYPE_COMBINED) || (activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE && (activity.UnitName != FIFPConstants.UNITTYPE_MOL && activity.UnitName != FIFPConstants.UNITTYPE_BYPASS_MOL)))
                lstDeletedLSDs = activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();
            else
                lstDeletedLSDs = activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == false).ToList<FIFPAppointment>();

            return lstDeletedLSDs;
        }
        #endregion

        #region Modified datagrid change
        private void ModifiedActivityDatagridSelectionChange(DataGrid activityGrid)
        {
            ModifiedDataGrid = activityGrid;
            FIFPAppointment activity = (FIFPAppointment)activityGrid.SelectedItem;
            if (activity != null)
            {
                if (activity.LsdReason == "SIMOPS applied")
                {
                    IsCancelSIMOPSEnabled = true;
                }
                else if (activity.LsdReason == "Crossing line applied")
                {
                    IsCancelCrossLineEnabled = true;
                }
                else if (SelectedActivity != null)
                {
                    IsLSDRevertEnabled = true;
                    IsApplySIMOPSEnabled = IsApplyCrossLineEnabled = false;
                }
                else
                {
                    if (ModifiedDataGrid != null)
                        ModifiedDataGrid.SelectedIndex = -1;
                    ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD_ACTIVITY);
                }
                ModifiedSelectedActivity = activity;
            }
        }

        #endregion

        #region Apply SIMOPS
        private void ReloadTimelineViewBySIMOPS(Button btnSIMOPS)
        {
            IsSIMOPS = true;
            if (SelectedActivity != null)
            {
                popup = new PercentagePopup();
                popup.Closed += new EventHandler(popup_Closed);
                popup.Show();
            }
            else
                MessageBox.Show("Please select Activity");
        }

        void popup_Closed(object sender, EventArgs e)
        {

        }
        #endregion

        #region Apply Crossing line
        private void ReloadTimelineViewByCrossingLine(Button btnSIMOPS)
        {
            IsSIMOPS = false;
            if (SelectedActivity != null)
            {
                if (SelectedActivity != null)
                {
                    popup = new PercentagePopup();
                    popup.Closed += new EventHandler(popup_Closed);
                    popup.Show();
                }
            }
            else
                MessageBox.Show("Please select Activity");
        }
        #endregion

        #region Location datagrid selection changed
        private void LSDLocationGridSelectionChange(DataGrid locationGrid)
        {
            //ServiceLocator.Get<FilterVM>().SelectedDivision = ServiceLocator.Get<FilterVM>().DivisionList[0];
            if (locationGrid != null && locationGrid.SelectedItem != null)
            {

                if (FilteredActivityListWithSelectedUnit != null && FilteredActivityListWithSelectedUnit.Count > 0)
                {
                    if (ActivitiesDataGrid != null)
                        ActivitiesDataGrid.SelectedIndex = -1;
                }
                if (ModifiedLinkedShutdownList != null && ModifiedLinkedShutdownList.Count > 0)
                {
                    if (ModifiedDataGrid != null)
                        ModifiedDataGrid.SelectedIndex = -1;
                }
                IsEnabledRaducedCapacity = false;
                SelectedActivity = null;
                SelectedTreeViewUnit = null;
                ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
                IsCombinedTowerEnabled = false;
                if (ModifiedDataGrid != null)
                    ModifiedDataGrid.SelectedIndex = -1;
                IsApplyCrossLineEnabled = IsApplySIMOPSEnabled = IsCancelCrossLineEnabled = IsCancelSIMOPSEnabled = false;
                SelectedLSDLocation = locationGrid.SelectedItem as Unit;
                if (SelectedLSDLocation != null)
                {
                    //SelectedClosedString = SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS : string.Empty;
                    //ServiceLocator.Get<FilterVM>().IsDivisionEnabled = true;
                    if (SelectedLSDLocation.UnitType != FIFPConstants.UNITTYPE_TOWER)
                    {
                        IsApplyCrossLineEnabled = IsApplySIMOPSEnabled = IsCancelCrossLineEnabled = IsCancelSIMOPSEnabled = false;
                    }
                    if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                    {
                        ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked = true;
                    }
                    else
                        ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked = false;

                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL)
                        LoadTreeView(UnitList.Where(p => p.UnitID == SelectedLSDLocation.ParentUnitID).FirstOrDefault());
                    else
                        LoadTreeView(SelectedLSDLocation);

                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL)
                    {
                        if (ServiceLocator.Get<FilterVM>().SelectedLsdDivision != null && ServiceLocator.Get<FilterVM>().SelectedLsdDivision == "All")
                        {
                            ActivityListWithSelectedUnit = (from item in ShutdownPlans
                                                            where item.UnitName == SelectedLSDLocation.UnitName && (item.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || item.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)
                                                            select item).ToList<FIFPAppointment>();
                        }
                        else
                        {
                            ActivityListWithSelectedUnit = (from item in ShutdownPlans
                                                            where item.UnitName == SelectedLSDLocation.UnitName && item.Division == ServiceLocator.Get<FilterVM>().SelectedLsdDivision && (item.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || item.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)
                                                            select item).ToList<FIFPAppointment>();
                        }
                    }
                    else
                    {
                        if (ServiceLocator.Get<FilterVM>().SelectedLsdDivision != null && ServiceLocator.Get<FilterVM>().SelectedLsdDivision == "All")
                        {
                            ActivityListWithSelectedUnit = (from item in ShutdownPlans
                                                            where item.UnitName == SelectedLSDLocation.UnitName
                                                            select item).ToList<FIFPAppointment>();
                        }
                        else
                        {
                            ActivityListWithSelectedUnit = (from item in ShutdownPlans
                                                            where item.UnitName == SelectedLSDLocation.UnitName && item.Division == ServiceLocator.Get<FilterVM>().SelectedLsdDivision 
                                                            select item).ToList<FIFPAppointment>();
                        }
                    }

                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER)//Update modified grid when the tower activity has already applied simops.
                    {
                        ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>((from item in ActivityListWithSelectedUnit
                                                                                                where item.UnitName == SelectedLSDLocation.UnitName && (item.IsAppliedCrossingLine || item.IsAppliedLSDSimops)
                                                                                                select item));
                        //load activities grid which is not 
                        FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>(ActivityListWithSelectedUnit.Where(s => s.IsAppliedLSDSimops == false && s.IsAppliedCrossingLine == false).OrderBy(p => p.Start));
                    }
                    else
                    {
                        FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>(ActivityListWithSelectedUnit.OrderBy(s => s.Start));
                    }

                    BindScheduleView();
                }
            }
        }
        #endregion

        #region LoadTreeviewGrid
        private void LoadTreeviewGrid(Grid grdTreeView)
        {
            TreeViewGrid = grdTreeView;
        }
        #endregion

        #region Applicable for ReducedCapacity
        private bool IsApplicableForRC(Unit selectedUnit)
        {
            bool bRet = false;
            if (SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_MOL && (selectedUnit.UnitName == FIFPConstants.UNITTYPE_MOL || selectedUnit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL || (selectedUnit.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT)))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL && (selectedUnit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL || selectedUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM && (selectedUnit.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CSP_UNIT && (selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || selectedUnit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT && (selectedUnit.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT || selectedUnit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CP1_UNIT && (selectedUnit.UnitName == FIFPConstants.PLATFORM_CP1_UNIT || selectedUnit.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR))
                bRet = true;
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_SEPERATOR && (selectedUnit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR))
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_ERP_UNIT && selectedUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_NRP_UNIT && selectedUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT && selectedUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                bRet = true;
            else if (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_WIP_UNIT && (selectedUnit.UnitName == FIFPConstants.PLATFORM_WIP_UNIT || selectedUnit.UnitType == FIFPConstants.UNITTYPE_MODULE))
                bRet = true;
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_MODULE && (selectedUnit.UnitType == FIFPConstants.UNITTYPE_MODULE))
                bRet = true;
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR && (selectedUnit.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR))
                bRet = true;
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_RADIAL && (selectedUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL))
                bRet = true;
            else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PIPELINE && (selectedUnit.UnitName != FIFPConstants.UNITTYPE_MOL && selectedUnit.UnitName != FIFPConstants.UNITTYPE_BYPASS_MOL))
                bRet = true;
            return bRet;
        }
        #endregion

        #region Applicable for ReducedCapacity
        private bool IsApplicableForRCBySelectedActivity(FIFPAppointment selectedUnit)
        {
            bool bRet = true;
            if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_TOWER && selectedUnit.UnitType == FIFPConstants.UNITTYPE_WELL && selectedUnit.UnitType == FIFPConstants.UNITTYPE_STRING && (selectedUnit.UnitType == FIFPConstants.UNITTYPE_PIPELINE && (selectedUnit.UnitName == FIFPConstants.UNITTYPE_MOL || selectedUnit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)))
                bRet = false;
            return bRet;
        }
        #endregion

        #region LoadTreeView
        private void LoadTreeView(Unit selectedUnit)
        {
            if (selectedUnit != null)
            {
                TreeViewGrid.Children.Clear();
                TreeView treeView = new TreeView();
                treeView.Style = Application.Current.Resources["TreeViewStyleSMUR"] as Style;
                treeView.ItemContainerStyle = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                treeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(treeView_SelectedItemChanged);

                TreeViewItem rootItem = new TreeViewItem();
                rootItem.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                rootItem.Header = selectedUnit.UnitName;
                rootItem.Tag = selectedUnit;
                rootItem.Foreground = selectedUnit.UnitNameTextColor;
                rootItem.IsExpanded = true;
                treeView.Items.Add(rootItem);

                TreeViewGrid.Children.Add(treeView);

                if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_PIPELINE && selectedUnit.UnitName == FIFPConstants.UNITTYPE_MOL)
                    GetUnitNameListByMOL(selectedUnit.ChildUnitList, rootItem);
                else if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_PLATFORM && selectedUnit.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM)
                    GetUnitNameListByMOL(selectedUnit.ChildUnitList, rootItem);
                else if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_PLATFORM && selectedUnit.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)
                    GetGasUnitNameListByPlatform(selectedUnit.ChildUnitList, rootItem);
                else if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_PLATFORM || selectedUnit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                    GetUnitNameListByPlatform(selectedUnit.ChildUnitList, rootItem);
                else if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_TOWER || selectedUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                    GetUnitNameList(new List<Unit>() { selectedUnit }, rootItem, true);
                else
                    GetPipelineUnitNameList(selectedUnit.ChildUnitList, rootItem, selectedUnit.FluidType);//Radial or pipeline
            }
        }

        #region SearchByUnitName
        private void SearchByUnitName(object e)
        {
            var binding = txtSearch.GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();
            KeyEventArgs args = e as KeyEventArgs;
            if (args != null && args.Key == Key.Enter)
            {
                if (!string.IsNullOrEmpty(UnitName))
                {
                    if (CheckUnitNameValidation())
                    {
                        IsUnitNameExist = false;
                        NotifyPropertyChanged(() => UnitName);
                        Unit unit = UnitList.Where(s => s.UnitName.ToLower() == UnitName.ToLower()).FirstOrDefault();
                        if (unit != null)
                            LoadTreeView(unit);
                    }
                }
                else
                {
                    IsUnitNameExist = false;
                    NotifyPropertyChanged(() => UnitName);
                    LoadTreeView(SelectedLSDLocation);
                }
            }
        }
        #endregion

        // recursively search
        public TreeViewItem FindItemByHeaderRecursive(ItemCollection nodes, string searchFor)
        {
            foreach (TreeViewItem item in nodes)
            {
                if (item.Header.Equals(searchFor))
                    return item;
                if (item.Items.Count > 0)
                {
                    TreeViewItem result =
                    FindItemByHeaderRecursive(item.Items, searchFor);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }

        void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            SelectedTreeViewUnit = null;//If it is not applicable for RC,then we won't enable Reduced Capcity Button
            TreeView treeView = sender as TreeView;
            if (treeView != null && treeView.SelectedItem != null)
            {
                TreeViewItem item = treeView.SelectedItem as TreeViewItem;
                if (item != null && item.Tag != null)
                {
                    Unit unit = item.Tag as Unit;
                    if (unit != null && SelectedActivity != null && (SelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_CODE_CNST && SelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_CODE_TPC))
                    {
                        if (IsApplicableForRC(unit))
                        {
                            if (unit != null && SelectedActivity.LSDDeletedIds != null && SelectedActivity.LSDDeletedIds.Length > 0)
                            {
                                if (SelectedActivity != null)
                                    IsEnabledRaducedCapacity = true;

                                SelectedTreeViewUnit = unit;

                                RCUnitName = SelectedTreeViewUnit.UnitName;
                                OriginalCapacity = SelectedTreeViewUnit.Capacity;

                                ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == unit.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                                if (rc != null)
                                    ReducedUnitCapacity = Convert.ToString(rc.ReducedUnitCapacity);
                                else
                                    ReducedUnitCapacity = "0";
                            }
                            else
                            {
                                IsEnabledRaducedCapacity = false;
                                treeView.ClearSelection();
                                ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_LSD_UNIT, FIFPConstants.WARNINGMESSAGE_DELETE_ACTIVITY);
                            }
                        }
                        else
                        {
                            IsEnabledRaducedCapacity = false;
                            treeView.ClearSelection();
                        }
                    }
                    else
                    {
                        IsEnabledRaducedCapacity = false;
                        treeView.ClearSelection();
                    }
                    //else
                    //{
                    //    treeView.ClearSelection();
                    //    ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_ACTIVITY, FIFPConstants.WARNINGMESSAGE_SELECT_ACTIVITY);
                    //}
                }
            }
        }
        #endregion

        #region GetUnitNameListByMOL
        private void GetUnitNameListByMOL(List<Unit> lstUnits, TreeViewItem rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                TreeViewItem usscNode = new TreeViewItem();
                usscNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                if (unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM || unit.UnitType == FIFPConstants.UNITTYPE_PIPELINE)
                {
                    usscNode.Header = unit.UnitName;
                    usscNode.Tag = unit;
                    usscNode.Foreground = unit.UnitNameTextColor;
                    usscNode.IsExpanded = false;
                    rootItem.Items.Add(usscNode);

                    foreach (Unit platformUnit in unit.ChildUnitList)
                    {
                        TreeViewItem platformNode = new TreeViewItem();
                        if (platformUnit.UnitType == FIFPConstants.UNITTYPE_PLATFORM || platformUnit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR || platformUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                        {
                            platformNode.Header = platformUnit.UnitName;
                            platformNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                            platformNode.Tag = platformUnit;
                            platformNode.Foreground = platformUnit.UnitNameTextColor;
                            platformNode.IsExpanded = false;
                            usscNode.Items.Add(platformNode);

                            foreach (Unit childUnit in platformUnit.ChildUnitList)
                            {
                                TreeViewItem radialNode = new TreeViewItem();
                                radialNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                                if (childUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                                {
                                    radialNode.Header = childUnit.UnitName;
                                    radialNode.Tag = childUnit;
                                    radialNode.Foreground = childUnit.UnitNameTextColor;
                                    radialNode.IsExpanded = false;
                                    platformNode.Items.Add(radialNode);
                                }
                                else if (childUnit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR)
                                {
                                    radialNode.Header = childUnit.UnitName;
                                    radialNode.Tag = childUnit;
                                    radialNode.Foreground = childUnit.UnitNameTextColor;
                                    radialNode.IsExpanded = false;
                                    platformNode.Items.Add(radialNode);
                                }
                                //GetTowerUnitNameList(radialUnit.ChildUnitList, radialNode);
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region GetUnitNameListByUSSC
        private void GetUnitNameListByUSOSSP(List<Unit> lstUnits, TreeViewItem rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                TreeViewItem usscNode = new TreeViewItem();
                usscNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                usscNode.Header = unit.UnitName;
                usscNode.Tag = unit;
                usscNode.Foreground = unit.UnitNameTextColor;
                usscNode.IsExpanded = false;
                rootItem.Items.Add(usscNode);

                foreach (Unit platformUnit in unit.ChildUnitList)
                {
                    TreeViewItem platformNode = new TreeViewItem();
                    platformNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                    if (platformUnit.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                    {
                        platformNode.Header = platformUnit.UnitName;
                        platformNode.Tag = platformUnit;
                        platformNode.Foreground = platformUnit.UnitNameTextColor;
                        platformNode.IsExpanded = false;
                        usscNode.Items.Add(platformNode);

                        foreach (Unit radialUnit in platformUnit.ChildUnitList)
                        {
                            TreeViewItem radialNode = new TreeViewItem();
                            radialNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                            if (radialUnit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                            {
                                radialNode.Header = radialUnit.UnitName;
                                radialNode.Tag = radialUnit;
                                radialNode.Foreground = radialUnit.UnitNameTextColor;
                                radialNode.IsExpanded = false;
                                platformNode.Items.Add(radialNode);
                            }
                            //GetTowerUnitNameList(radialUnit.ChildUnitList, radialNode);
                        }
                    }
                }
            }
        }
        #endregion

        #region GetUnitNameListByPlatform
        private void GetUnitNameListByPlatform(List<Unit> lstUnits, TreeViewItem rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                TreeViewItem radialNode = new TreeViewItem();
                radialNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                if (unit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                {
                    radialNode.Header = unit.UnitName;
                    radialNode.Tag = unit;
                    radialNode.Foreground = unit.UnitNameTextColor;
                    radialNode.IsExpanded = false;
                    rootItem.Items.Add(radialNode);
                }
                else if (unit.UnitType == FIFPConstants.UNITTYPE_SEPERATOR)
                {
                    radialNode.Header = unit.UnitName;
                    radialNode.Tag = unit;
                    radialNode.Foreground = unit.UnitNameTextColor;
                    radialNode.IsExpanded = false;
                    rootItem.Items.Add(radialNode);
                }
                else if (unit.UnitType == FIFPConstants.UNITTYPE_MODULE)
                {
                    radialNode.Header = unit.UnitName;
                    radialNode.Tag = unit;
                    radialNode.Foreground = unit.UnitNameTextColor;
                    radialNode.IsExpanded = false;
                    rootItem.Items.Add(radialNode);
                }
                //GetTowerUnitNameList(unit.ChildUnitList, radialNode);
            }
        }
        #endregion

        #region GetGasUnitNameListByPlatform
        private void GetGasUnitNameListByPlatform(List<Unit> lstUnits, TreeViewItem rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                TreeViewItem radialNode = new TreeViewItem();
                radialNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                if (unit.UnitType == FIFPConstants.UNITTYPE_RADIAL)
                {
                    radialNode.Header = unit.UnitName;
                    radialNode.Tag = unit;
                    radialNode.Foreground = unit.UnitNameTextColor;
                    radialNode.IsExpanded = false;
                    rootItem.Items.Add(radialNode);
                    foreach (Unit towerUnit in unit.ChildUnitList)
                    {
                        TreeViewItem towerNode = new TreeViewItem();
                        towerNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                        towerNode.Header = towerUnit.UnitName;
                        towerNode.Tag = towerUnit;
                        towerNode.Foreground = towerUnit.UnitNameTextColor;
                        towerNode.IsExpanded = false;
                        radialNode.Items.Add(towerNode);
                        foreach (Unit wellUnit in towerUnit.ChildUnitList)
                        {
                            TreeViewItem childNode = new TreeViewItem();
                            childNode.Header = wellUnit.UnitName;
                            childNode.Tag = wellUnit;
                            childNode.Foreground = wellUnit.UnitNameTextColor;
                            childNode.IsExpanded = false;
                            towerNode.Items.Add(childNode);
                        }
                    }
                }
                else if (unit.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR)
                {
                    radialNode.Header = unit.UnitName;
                    radialNode.Tag = unit;
                    radialNode.Foreground = unit.UnitNameTextColor;
                    radialNode.IsExpanded = false;
                    rootItem.Items.Add(radialNode);
                }
                //GetTowerUnitNameList(unit.ChildUnitList, radialNode);
            }
        }
        #endregion

        #region Get GetTowerUnitNameList
        private void GetTowerUnitNameList(List<Unit> lstUnits, TreeViewItem rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    TreeViewItem towerNode = new TreeViewItem();
                    towerNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                    towerNode.Header = unit.UnitName;
                    towerNode.Tag = unit;
                    towerNode.Foreground = unit.UnitNameTextColor;
                    towerNode.IsExpanded = false;
                    rootItem.Items.Add(towerNode);

                    foreach (Unit childUnit in unit.ChildUnitList)
                    {
                        TreeViewItem node = new TreeViewItem();
                        node.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                        node.Header = childUnit.UnitName;
                        node.Tag = childUnit;
                        node.Foreground = childUnit.UnitNameTextColor;
                        node.IsExpanded = false;
                        if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                        {
                            foreach (Unit stringUnit in childUnit.ChildUnitList)
                            {
                                TreeViewItem childNode = new TreeViewItem();
                                childNode.Header = stringUnit.UnitName;
                                childNode.Tag = stringUnit;
                                childNode.Foreground = stringUnit.UnitNameTextColor;
                                childNode.IsExpanded = false;
                                node.Items.Add(childNode);
                            }
                        }
                        towerNode.Items.Add(node);
                    }
                }
                GetTowerUnitNameList(unit.ChildUnitList, rootItem);
            }
        }
        #endregion

        #region Get Treeview UnitList
        private void GetUnitNameList(List<Unit> lstUnits, TreeViewItem rootItem, bool bInitial)
        {
            foreach (Unit unit in lstUnits)
            {
                if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    TreeViewItem towerNode = new TreeViewItem();
                    towerNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                    if (bInitial)
                    {
                        TreeViewItem ctItem = FindItemByHeaderRecursive(rootItem.Items, unit.UnitName);
                        if (ctItem != null)
                            IsNodeExists = true;
                        else
                            IsNodeExists = false;
                        if (lstUnits != null && lstUnits[0] != null && lstUnits[0].ChildUnitList != null && lstUnits[0].ChildUnitList.Count > 0)
                        {
                            List<Unit> childUnits = new List<Unit>();
                            if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))
                            {
                                if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                                {
                                    childUnits = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                                }
                                else if(SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && ((unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))))
                                {
                                    childUnits = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                                }
                                else
                                {
                                    List<Unit> parentUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                                    List<Unit> filterdList = new List<Unit>();
                                    if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                                        filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                                    else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                                        filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                                    else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                                        filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                                    else
                                        filterdList = parentUnitList;

                                    childUnits = filterdList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                                }
                            }
                            else
                            {
                                childUnits = lstUnits[0].ChildUnitList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                            }
                            foreach (Unit childUnit in childUnits)
                            {
                                if (childUnit.UnitType != FIFPConstants.UNITTYPE_TOWER)
                                {
                                    TreeViewItem node = new TreeViewItem();
                                    node.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                                    node.Header = childUnit.UnitName;
                                    node.Tag = childUnit;
                                    node.Foreground = childUnit.UnitNameTextColor;
                                    node.IsExpanded = false;
                                    rootItem.Items.Add(node);
                                    if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                                    {
                                        foreach (Unit stringUnit in childUnit.ChildUnitList)
                                        {
                                            TreeViewItem childNode = new TreeViewItem();
                                            childNode.Header = stringUnit.UnitName;
                                            childNode.Tag = stringUnit;
                                            childNode.Foreground = stringUnit.UnitNameTextColor;
                                            childNode.IsExpanded = false;
                                            node.Items.Add(childNode);
                                        }
                                    }
                                }
                            }
                        }
                        bInitial = false;
                    }
                    else
                    {
                        towerNode.Header = unit.UnitName;
                        towerNode.Tag = unit;
                        towerNode.Foreground = unit.UnitNameTextColor;
                        towerNode.IsExpanded = false;

                        TreeViewItem ctItem = FindItemByHeaderRecursive(rootItem.Items, unit.UnitName);
                        if (ctItem != null)
                            IsNodeExists = true;
                        else
                            IsNodeExists = false;
                        if (!IsNodeExists)
                            rootItem.Items.Add(towerNode);

                    }

                    List<Unit> childUnitList = new List<Unit>();
                    if (!IsNodeExists && (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40)))
                    {
                        if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                        {
                            childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                        else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && ((unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))))
                        {
                            childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                        else
                        {
                            List<Unit> parentUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                            List<Unit> filterdList = new List<Unit>();
                            if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else
                                filterdList = parentUnitList;

                            childUnitList = filterdList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                    }
                    else
                        childUnitList = unit.ChildUnitList.OrderByDescending(s => s.UnitType).ToList<Unit>();

                    foreach (Unit childUnit in childUnitList)
                    {
                        TreeViewItem node = new TreeViewItem();
                        node.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                        node.Header = childUnit.UnitName;
                        node.Tag = childUnit;
                        node.Foreground = childUnit.UnitNameTextColor;
                        node.IsExpanded = false;
                        if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                        {
                            foreach (Unit stringUnit in childUnit.ChildUnitList)
                            {
                                TreeViewItem childNode = new TreeViewItem();
                                childNode.Header = stringUnit.UnitName;
                                childNode.Tag = stringUnit;
                                childNode.Foreground = stringUnit.UnitNameTextColor;
                                childNode.IsExpanded = false;
                                node.Items.Add(childNode);
                            }
                        }
                        towerNode.Items.Add(node);
                    }
                }
                if (!IsNodeExists && (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40)))
                {
                    //List<Unit> childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                    List<Unit> childUnitList = new List<Unit>();
                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                    {
                        childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && ((unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))))
                    {
                        childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    else
                    {
                        List<Unit> parentUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                        List<Unit> filterdList = new List<Unit>();
                        if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else
                            filterdList = parentUnitList;

                        childUnitList = filterdList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    GetUnitNameList(childUnitList, rootItem, bInitial);
                }
                else
                    GetUnitNameList(unit.ChildUnitList, rootItem, bInitial);
            }
        }
        #endregion

        #region Get Pipeline radial UnitList
        private void GetPipelineUnitNameList(List<Unit> lstUnits, TreeViewItem rootItem, string fluidType)
        {
            foreach (Unit unit in lstUnits)
            {
                if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == fluidType || unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD))
                {
                    TreeViewItem towerNode = new TreeViewItem();
                    towerNode.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                    towerNode.Header = unit.UnitName;
                    towerNode.Tag = unit;
                    towerNode.Foreground = unit.UnitNameTextColor;
                    towerNode.IsExpanded = false;

                    TreeViewItem ctItem = FindItemByHeaderRecursive(rootItem.Items, unit.UnitName);
                    if (ctItem != null)
                        IsNodeExists = true;
                    else
                        IsNodeExists = false;
                    if (!IsNodeExists)
                        rootItem.Items.Add(towerNode);


                    List<Unit> childUnitList = new List<Unit>();
                    if (!IsNodeExists && (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40)))
                    {
                        if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                        {
                            childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                        else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && ((unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))))
                        {
                            childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                        else
                        {
                            List<Unit> parentUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                            List<Unit> filterdList = new List<Unit>();
                            if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                                filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                            else
                                filterdList = parentUnitList;

                            childUnitList = filterdList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                        }
                    }
                    else
                        childUnitList = unit.ChildUnitList.OrderByDescending(s => s.UnitType).ToList<Unit>();

                    foreach (Unit childUnit in childUnitList)
                    {
                        if (childUnit.FluidType == fluidType)
                        {
                            TreeViewItem node = new TreeViewItem();
                            node.Style = Application.Current.Resources["TreeViewItemStyle1"] as Style;
                            node.Header = childUnit.UnitName;
                            node.Tag = childUnit;
                            node.Foreground = childUnit.UnitNameTextColor;
                            node.IsExpanded = false;
                            if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                            {
                                foreach (Unit stringUnit in childUnit.ChildUnitList)
                                {
                                    TreeViewItem childNode = new TreeViewItem();
                                    childNode.Header = stringUnit.UnitName;
                                    childNode.Tag = stringUnit;
                                    childNode.Foreground = stringUnit.UnitNameTextColor;
                                    childNode.IsExpanded = false;
                                    node.Items.Add(childNode);
                                }
                            }
                            towerNode.Items.Add(node);
                        }
                    }
                }
                if (!IsNodeExists && (unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40)))
                {
                    //List<Unit> childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                    List<Unit> childUnitList = new List<Unit>();
                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                    {
                        childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && ((unit.UnitType == FIFPConstants.UNITTYPE_TOWER && (unit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || unit.UnitName == FIFPConstants.TOWER_UT_22A || unit.UnitName == FIFPConstants.TOWER_UT_12A || unit.UnitName == FIFPConstants.TOWER_UT_40))))
                    {
                        childUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    else
                    {
                        List<Unit> parentUnitList = UnitList.Where(s => s.UnitName == unit.UnitName).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                        List<Unit> filterdList = new List<Unit>();
                        if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS)
                            filterdList = parentUnitList.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_GAS || s.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || s.FluidType == FIFPConstants.TOWERTYPE_MANIFOLD).ToList<Unit>();
                        else
                            filterdList = parentUnitList;

                        childUnitList = filterdList.OrderByDescending(s => s.UnitType).ToList<Unit>();
                    }
                    GetPipelineUnitNameList(childUnitList, rootItem, fluidType);
                }
                else
                    GetPipelineUnitNameList(unit.ChildUnitList, rootItem, fluidType);
            }
        }
        #endregion

        #region HidePopup
        private void HidePopup(Button btnCancel)
        {
            CapacityPercentage = "100";
            if (popup != null)
                popup.Close();
            ReducedUnitCapacity = "0";
            if (capacityPopup != null)
                capacityPopup.Close();
        }
        #endregion

        #region ShowPopup
        private void ShowPopup(Button btnShow)
        {
            ApplySIMOPSorCrossingLine();
        }

        private void ApplySIMOPSorCrossingLine()
        {
            if (CheckPercentageValidation())
            {
                if (SelectedActivity != null)
                {
                    if (IsSIMOPS)
                    {
                        //We have to open all the linked shutdowns corresponding to the activity
                        //Default unit shutdown - open wells except RIG activity wells. Open pipeline also.
                        List<int> wellRigUnitIds = SelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && (s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)).Select(s => s.UnitID).Distinct().ToList<int>();//Open Pipeline and Well activities
                        List<int> allUnitIds = SelectedActivity.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();
                        List<int> lsdUnitIds = new List<int>(allUnitIds.Except(wellRigUnitIds));

                        //List<int> stringUnitIds = UnitList.Where(u => wellUnitIds.Any(s => s.Equals(u.ParentUnitID))).Select(p => p.UnitID).ToList<int>();
                        //stringUnitIds.AddRange(SelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_PIPELINE).Select(s => s.UnitID).Distinct().ToList<int>());//Add Pipeline activities
                        //stringUnitIds - It has both pipeline and string unitIds without having RIG activities strings
                        SelectedActivity.LsdReason = "SIMOPS applied";
                        SelectedActivity.IsAppliedLSDSimops = true;

                        SelectedActivity.IsModified = SelectedActivity.IsModified == 1 ? 1 : 0;
                        //if (SelectedLSDLocation.UnitType != FIFPConstants.UNITTYPE_WELL && (SelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG && SelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RGL))//Rig Activity
                        //{
                        //    SelectedActivity.UnitStatus = "Open";
                        //    SelectedActivity.IsDefaultUnitShutdown = false;
                        //}

                        if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))//Rig Activity
                        {
                            SelectedActivity.SelectedString = string.Empty;
                        }
                        else
                        {
                            SelectedActivity.SelectedString = SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_OIL ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS : SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_WATER ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS : SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_GAS ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_GASSTRINGS : FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS;
                            SelectedActivity.UnitStatus = "Open";
                            SelectedActivity.IsDefaultUnitShutdown = false;
                        }

                        List<int> lsdIds = SelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_TOWER).Select(p => p.UnitID).ToList<int>();
                        string Ids = string.Join(",", lsdIds);
                        SelectedActivity.LSDDeletedIds = Ids;
                        foreach (FIFPAppointment appointment in SelectedActivity.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID)))) //Apply capacity percentage for string and pipeline units
                        {
                            appointment.IsLinkedShutdownPlan = false;
                            if (appointment.UnitType == FIFPConstants.UNITTYPE_STRING)//only string units is applicable for apply percentage
                                appointment.CapacityPercentage = Math.Round(Convert.ToDouble((Convert.ToDouble(CapacityPercentage) / 100)), 2);
                        }
                    }
                    else
                    {
                        List<int> towerChildUnits = GetTowerChildUnitsExceptPipeline(SelectedActivity.UnitID);//get well and string units except pipeline because we have to open pipeline from default unit shutdown when we apply crossing line
                        List<int> allUnitIds = SelectedActivity.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();//select overall units
                        List<int> lsdUnitIds = new List<int>(allUnitIds.Except(towerChildUnits));//

                        /*
                        List<int> wellUnitIds = SelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && s.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG).Select(s => s.UnitID).Distinct().ToList<int>();
                        List<int> parentUnitWellIds = UnitList.Where(u => u.ParentUnitID == SelectedActivity.UnitID && u.UnitType == FIFPConstants.UNITTYPE_WELL).Select(p => p.UnitID).ToList<int>();
                        wellUnitIds = new List<int>(wellUnitIds.Except(parentUnitWellIds));
                        List<int> stringUnitIds = UnitList.Where(u => wellUnitIds.Any(s => s.Equals(u.ParentUnitID))).Select(p => p.UnitID).ToList<int>();*/

                        SelectedActivity.LsdReason = "Crossing line applied";
                        SelectedActivity.IsAppliedCrossingLine = true;
                        SelectedActivity.IsDefaultUnitShutdown = false;
                        SelectedActivity.IsModified = SelectedActivity.IsModified == 1 ? 1 : 0;
                        List<int> lsdIds = SelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_TOWER).Select(p => p.UnitID).ToList<int>();
                        string Ids = string.Join(",", lsdIds);
                        SelectedActivity.LSDDeletedIds = Ids;

                        foreach (FIFPAppointment appointment in SelectedActivity.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID))))
                        {
                            appointment.IsLinkedShutdownPlan = false;
                            if (appointment.UnitType == FIFPConstants.UNITTYPE_STRING)//only string units is applicable for apply percentage
                                appointment.CapacityPercentage = Math.Round(Convert.ToDouble((Convert.ToDouble(CapacityPercentage) / 100)), 2);
                        }
                    }
                }

                ModifiedLinkedShutdownList.Add(SelectedActivity);

                //Remove deleted lsd unit ids from modified activities grid if we apply simops for the selected activity.
                List<FIFPAppointment> lsdTowerUnits = SelectedActivity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER).ToList<FIFPAppointment>();
                ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(ModifiedLinkedShutdownList.Except(ModifiedLinkedShutdownList.Intersect(lsdTowerUnits)));


                FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>(FilteredActivityListWithSelectedUnit.Where(f => f.PlanID != SelectedActivity.PlanID).OrderBy(s => s.Start));

                //Load Timeline View
                List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();
                foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
                {
                    lsdPlans.Add(appointment);
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                    lsdPlans.AddRange(appointment.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));// Need to check IsLinkedShutDown = true
                }
                FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lsdPlans);//we have to update the plans with this list for retaining
                LoadTimelineView(lsdPlans);

                //Reset properties
                IsApplySIMOPSEnabled = false;
                IsApplyCrossLineEnabled = false;
                _validationResults.Clear();
                CapacityPercentage = "100";
                popup.Close();
            }
        }
        #endregion

        #region CancelSIMOPS
        private void CancelSIMOPS(Button btnCancel)
        {
            if (ModifiedSelectedActivity != null)
            {
                /*List<int> wellUnitIds = ModifiedSelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && s.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG).Select(s => s.UnitID).Distinct().ToList<int>();
                List<int> stringUnitIds = unitList.Where(u => wellUnitIds.Any(s => s.Equals(u.ParentUnitID))).Select(p => p.UnitID).ToList<int>();

                List<int> wellUnitIds = ModifiedSelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && s.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG).Select(s => s.UnitID).Distinct().ToList<int>();//Open Pipeline and Well activities
                List<int> stringUnitIds = UnitList.Where(u => wellUnitIds.Any(s => s.Equals(u.ParentUnitID))).Select(p => p.UnitID).ToList<int>();
                stringUnitIds.AddRange(ModifiedSelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_PIPELINE).Select(s => s.UnitID).Distinct().ToList<int>());//Add Pipeline activities*/

                List<int> wellRigUnitIds = ModifiedSelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && (s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)).Select(s => s.UnitID).Distinct().ToList<int>();//Open Pipeline and Well activities
                List<int> allUnitIds = ModifiedSelectedActivity.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();//select overall units
                List<int> lsdUnitIds = new List<int>(allUnitIds.Except(wellRigUnitIds));


                //if (SelectedLSDLocation.UnitType != FIFPConstants.UNITTYPE_WELL && (ModifiedSelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG && ModifiedSelectedActivity.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RGL))//Rig Activity
                if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))//Rig Activity
                {
                    SelectedActivity.SelectedString = SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_OIL ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS : SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_WATER ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS : SelectedActivity.FluidType == FIFPConstants.FLUIDTYPE_GAS ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_GASSTRINGS : FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS;
                }
                else
                {
                    if (ModifiedSelectedActivity.UnitStatus == "Open")
                    {
                        ActivityType activityCode = ServiceLocator.Get<ImportVM>().ActivityCodeDivisionList.Where(s => s.Name == ModifiedSelectedActivity.ActivityCode && s.ActivityStatus != "Open").FirstOrDefault();
                        if (activityCode != null)
                        {
                            ModifiedSelectedActivity.UnitStatus = activityCode.ActivityStatus;
                            ModifiedSelectedActivity.ActivityId = activityCode.Id;
                        }
                    }
                }

                ModifiedSelectedActivity.IsModified = ModifiedSelectedActivity.IsModified == 1 ? 1 : 0;
                ModifiedSelectedActivity.IsAppliedLSDSimops = false;
                ModifiedSelectedActivity.IsDefaultUnitShutdown = true;
                ModifiedSelectedActivity.LSDDeletedIds = string.Empty;
                ModifiedSelectedActivity.LsdReason = string.Empty;
                foreach (FIFPAppointment appointment in ModifiedSelectedActivity.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID))))
                {
                    appointment.IsLinkedShutdownPlan = true;
                    if (appointment.UnitType == FIFPConstants.UNITTYPE_STRING)//only string units is applicable for apply percentage
                        appointment.CapacityPercentage = 1;
                }
            }
            ModifiedSelectedActivity.LsdReason = string.Empty;

            List<FIFPAppointment> selectedLocationActivityList = new List<FIFPAppointment>(FilteredActivityListWithSelectedUnit);
            selectedLocationActivityList.AddRange(ModifiedLinkedShutdownList.Where(f => f.PlanID == ModifiedSelectedActivity.PlanID));
            FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>(selectedLocationActivityList.OrderBy(s => s.Start));

            //FilteredActivityListWithSelectedUnit.AddRange(ModifiedLinkedShutdownList.Where(f => f.PlanID == ModifiedSelectedActivity.PlanID));
            ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(ModifiedLinkedShutdownList.Where(f => f.PlanID != ModifiedSelectedActivity.PlanID));
            //Load Timeline View
            List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();
            foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
            {
                lsdPlans.Add(appointment);
                appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                lsdPlans.AddRange(appointment.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));// Need to check IsLinkedShutDown = true
            }
            IsCancelSIMOPSEnabled = false;
            if (ModifiedLinkedShutdownList != null && ModifiedLinkedShutdownList.Count == 0)
                IsCancelSIMOPSEnabled = IsCancelCrossLineEnabled = false;
            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lsdPlans);//we have to update the plans with this list for retaining
            LoadTimelineView(lsdPlans);
        }
        #endregion

        #region CancelCrossingLine
        private void CancelCrossingLine(Button btnCancel)
        {
            //TODO Make this as Generic function
            if (ModifiedSelectedActivity != null)
            {
                /*
                List<int> wellUnitIds = ModifiedSelectedActivity.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && s.ActivityCode != FIFPConstants.ACTIVITY_TYPE_RIG).Select(s => s.UnitID).Distinct().ToList<int>();
                List<int> parentUnitWellIds = UnitList.Where(u => u.ParentUnitID == ModifiedSelectedActivity.UnitID && u.UnitType == FIFPConstants.UNITTYPE_WELL).Select(p => p.UnitID).ToList<int>();
                wellUnitIds = new List<int>(wellUnitIds.Except(parentUnitWellIds));
                List<int> stringUnitIds = UnitList.Where(u => wellUnitIds.Any(s => s.Equals(u.ParentUnitID))).Select(p => p.UnitID).ToList<int>();*/


                List<int> towerChildUnits = GetTowerChildUnitsExceptPipeline(ModifiedSelectedActivity.UnitID);//get well and string units except pipeline because we have to open pipeline from default unit shutdown when we apply crossing line
                List<int> allUnitIds = ModifiedSelectedActivity.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();//select overall units
                List<int> lsdUnitIds = new List<int>(allUnitIds.Except(towerChildUnits));//



                ModifiedSelectedActivity.LsdReason = string.Empty;
                ModifiedSelectedActivity.IsModified = ModifiedSelectedActivity.IsModified == 1 ? 1 : 0;
                ModifiedSelectedActivity.IsAppliedCrossingLine = false;
                ModifiedSelectedActivity.IsDefaultUnitShutdown = true;
                ModifiedSelectedActivity.LSDDeletedIds = string.Empty;
                foreach (FIFPAppointment appointment in ModifiedSelectedActivity.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID))))
                {
                    appointment.IsLinkedShutdownPlan = true;
                    if (appointment.UnitType == FIFPConstants.UNITTYPE_STRING)//only string units is applicable for apply percentage
                        appointment.CapacityPercentage = 1;
                }
            }
            ModifiedSelectedActivity.LsdReason = string.Empty;

            FilteredActivityListWithSelectedUnit.AddRange(ModifiedLinkedShutdownList.Where(f => f.PlanID == ModifiedSelectedActivity.PlanID));
            ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(ModifiedLinkedShutdownList.Where(f => f.PlanID != ModifiedSelectedActivity.PlanID));
            //Load Timeline View
            List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();
            foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
            {
                lsdPlans.Add(appointment);
                appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                lsdPlans.AddRange(appointment.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));
            }
            IsCancelCrossLineEnabled = false;
            if (ModifiedLinkedShutdownList != null && ModifiedLinkedShutdownList.Count == 0)
                IsCancelSIMOPSEnabled = IsCancelCrossLineEnabled = false;
            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lsdPlans);//we have to update the plans with this list for retaining
            LoadTimelineView(lsdPlans);
        }
        #endregion

        #region Load Textbox
        TextBox txtSearch = null;
        private void LoadTextBox(TextBox txtBox)
        {
            txtSearch = txtBox;
        }
        #endregion

        #region CheckPercentageValidation
        private bool CheckPercentageValidation()
        {
            bool bRet = true;
            CapacityPercentage = txtPercentage.Text.Trim();
            if (!Regex.IsMatch(txtPercentage.Text.Trim(), FIFPConstants.RegularExpression))
            {
                bRet = false;
                txtPercentage.Focus();
                NotifyPropertyChanged(() => CapacityPercentage);
            }
            else if (!string.IsNullOrEmpty(Convert.ToString(CapacityPercentage)) && (Convert.ToDouble(CapacityPercentage) < 0 || Convert.ToDouble(CapacityPercentage) > 100))
            {
                bRet = false;
                txtPercentage.Focus();
                NotifyPropertyChanged(() => CapacityPercentage);
            }
            else
            {
                bRet = true;
                NotifyPropertyChanged(() => CapacityPercentage);
            }
            return bRet;
        }
        #endregion

        #region CheckPercentageValidation
        private bool CheckReducedCapacityValidation()
        {
            bool bRet = true;
            ReducedUnitCapacity = txtRC.Text.Trim();
            if (!Regex.IsMatch(txtRC.Text, FIFPConstants.RegularExpression))
            {
                bRet = false;
                txtRC.Focus();
                NotifyPropertyChanged(() => ReducedUnitCapacity);
            }
            else if (Convert.ToDouble(ReducedUnitCapacity) > Convert.ToDouble(OriginalCapacity))
            {
                bRet = false;
                txtRC.Focus();
                NotifyPropertyChanged(() => ReducedUnitCapacity);
            }
            else
            {
                bRet = true;
                NotifyPropertyChanged(() => ReducedUnitCapacity);
            }
            return bRet;
        }
        #endregion

        #region CheckUnitNameValidation
        private bool CheckUnitNameValidation()
        {
            bool bRet = true;

            //if (string.IsNullOrEmpty(UnitName))
            //{
            //    bRet = false;
            //    IsUnitNameExist = false;
            //    NotifyPropertyChanged(() => UnitName);
            //}
            if (!string.IsNullOrEmpty(UnitName) && UnitList.Where(s => s.UnitName.ToLower() == UnitName.ToLower()).FirstOrDefault() == null)
            {
                bRet = false;
                IsUnitNameExist = true;
                NotifyPropertyChanged(() => UnitName);
            }
            //else
            //{
            //    bRet = true;
            //    IsUnitNameExist = false;
            //    NotifyPropertyChanged(() => UnitName);
            //}
            return bRet;
        }

        #region Reduce unit capacity
        private void ReduceUnitCapacity(Button btnReduce)
        {
            ApplyReducedCapacity();
        }

        private void ReduceUnitCapacityKeyDown(object e)
        {
            KeyEventArgs args = e as KeyEventArgs;
            if (args != null && args.Key == Key.Enter)
            {
                //ReducedUnitCapacity = Convert.ToDouble(txtRC.Text);
                ApplyReducedCapacity();
            }
        }

        private void ApplyReducedCapacity()
        {
            if (CheckReducedCapacityValidation())
            {
                ReducedCapacity capacity = new ReducedCapacity();
                capacity.ScenarioId = ServiceLocator.Get<ImportVM>().CurrentScenarioId;
                if (SelectedActivity != null)
                {
                    if (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST)
                    {
                        capacity.UnitId = SelectedActivity.UnitID;
                        capacity.ParentUnitId = SelectedActivity.UnitID;
                    }
                    else
                    {
                        capacity.UnitId = SelectedTreeViewUnit.UnitID;
                        capacity.ParentUnitId = SelectedActivity.UnitID;
                    }
                    capacity.PlanId = SelectedActivity.PlanID;
                    capacity.StartDate = SelectedActivity.Start;
                    capacity.EndDate = SelectedActivity.End;
                }
                capacity.OriginalUnitCapacity = OriginalCapacity;
                capacity.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);

                if (ReducedCapacityList != null && !ReducedCapacityList.Contains(capacity))
                {
                    ReducedCapacityList.Add(capacity);
                    if (!ReducedCapacityBindList.Contains(capacity))
                    {
                        //Add modified grid in the right side
                        if (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST)
                        {
                            FIFPAppointment appointment = new FIFPAppointment() { UnitID = SelectedActivity.UnitID, LSDRCParentUnitId = SelectedActivity.UnitID, PlanID = SelectedActivity.PlanID, UnitName = SelectedActivity.UnitName, Start = SelectedActivity.Start, End = SelectedActivity.End, LsdReason = "Capacity reduced", ActivityCode = SelectedActivity.ActivityCode };
                            ModifiedLinkedShutdownList.Add(appointment);
                        }
                        else
                        {
                            FIFPAppointment appointment = new FIFPAppointment() { UnitID = SelectedTreeViewUnit.UnitID, LSDRCParentUnitId = SelectedActivity.UnitID, PlanID = SelectedActivity.PlanID, UnitName = SelectedTreeViewUnit.UnitName, Start = SelectedActivity.Start, End = SelectedActivity.End, LsdReason = "Capacity reduced", ActivityCode = SelectedActivity.ActivityCode };
                            ModifiedLinkedShutdownList.Add(appointment);
                        }
                        ReducedCapacityBindList.Add(capacity);
                    }
                    else
                    {
                        if (SelectedActivity != null && (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST))
                        {
                            ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedActivity.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                            if (rc != null)
                                rc.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);
                        }
                        else
                        {
                            if (SelectedActivity != null && SelectedTreeViewUnit != null)
                            {
                                ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedTreeViewUnit.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                                if (rc != null)
                                    rc.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);
                            }
                        }
                    }
                }
                else
                {
                    if (SelectedActivity != null && (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST))
                    {
                        ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedActivity.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                        if (rc != null)
                            rc.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);

                        ReducedCapacity rc1 = ReducedCapacityList.Where(s => s.UnitId == SelectedActivity.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                        if (rc1 != null)
                            rc1.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);

                    }
                    else
                    {
                        if (SelectedActivity != null && SelectedTreeViewUnit != null)
                        {
                            ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedTreeViewUnit.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                            if (rc != null)
                                rc.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);

                            ReducedCapacity rc1 = ReducedCapacityList.Where(s => s.UnitId == SelectedTreeViewUnit.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                            if (rc1 != null)
                                rc1.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);
                        }
                    }
                    //ReducedCapacity updatecapacity = ReducedCapacityList.Where(s => s.UnitId == capacity.UnitId).FirstOrDefault();
                    //if (updatecapacity != null)
                    //{
                    //    updatecapacity.ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);
                    //    ReducedCapacityBindList.Where(s => s.UnitId == capacity.UnitId).FirstOrDefault().ReducedUnitCapacity = Convert.ToDouble(ReducedUnitCapacity);
                    //}

                }
                capacityPopup.Close();
            }
        }

        void capacityPopup_Closed(object sender, EventArgs e)
        {

        }
        #endregion


        #region CalculateReducedCapacity
        private void CalculateReducedCapacity(object e)
        {
            if (_validationResults.Count > 0)
                _validationResults.Clear();
            if (SelectedActivity != null && (SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_TPC || SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_CODE_CNST))
            {
                ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedActivity.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                if (rc != null)
                    ReducedUnitCapacity = Convert.ToString(rc.ReducedUnitCapacity);
                else
                    ReducedUnitCapacity = "0";
            }
            else if (SelectedActivity != null && SelectedTreeViewUnit != null)
            {
                ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == SelectedTreeViewUnit.UnitID && s.PlanId == SelectedActivity.PlanID && s.ParentUnitId == SelectedActivity.UnitID && s.StartDate == SelectedActivity.Start && s.EndDate == SelectedActivity.End).FirstOrDefault();
                if (rc != null)
                    ReducedUnitCapacity = Convert.ToString(rc.ReducedUnitCapacity);
                else
                    ReducedUnitCapacity = "0";
            }

            capacityPopup = new ReducedCapacityPopup();
            capacityPopup.Closed += new EventHandler(capacityPopup_Closed);
            capacityPopup.Show();
        }
        #endregion

        #region Load Reduced Capcity Textbox
        TextBox txtRC = null;
        private void LoadRCTextBox(TextBox txtBox)
        {
            txtRC = txtBox;
        }
        #endregion

        #region Load Percentage Textbox
        TextBox txtPercentage = null;
        private void LoadPercentageTextbox(TextBox txtBox)
        {
            txtPercentage = txtBox;
        }
        #endregion

        private void PercentageByEnterKey(object e)
        {
            KeyEventArgs args = e as KeyEventArgs;
            if (args != null && args.Key == Key.Enter)
            {
                ApplySIMOPSorCrossingLine();
            }
        }

        #endregion

        #region Revert LSD Units to Gantt Chart
        private void RevertSDUnitToGanttChart(Button btnRevert)
        {
            if (ModifiedSelectedActivity != null)//Revert Deleted Ids
            {
                if (ModifiedSelectedActivity.LsdReason == "Capacity reduced")
                {

                    ReducedCapacity rc = ReducedCapacityBindList.Where(s => s.UnitId == ModifiedSelectedActivity.UnitID && s.PlanId == ModifiedSelectedActivity.PlanID && s.ParentUnitId == ModifiedSelectedActivity.LSDRCParentUnitId && s.StartDate == ModifiedSelectedActivity.Start && s.EndDate == ModifiedSelectedActivity.End).FirstOrDefault();
                    if (rc != null)
                        ReducedCapacityBindList.Remove(rc);

                    ReducedCapacity rc1 = ReducedCapacityList.Where(s => s.UnitId == ModifiedSelectedActivity.UnitID && s.PlanId == ModifiedSelectedActivity.PlanID && s.ParentUnitId == ModifiedSelectedActivity.LSDRCParentUnitId && s.StartDate == ModifiedSelectedActivity.Start && s.EndDate == ModifiedSelectedActivity.End).FirstOrDefault();
                    if (rc1 != null)
                        ReducedCapacityList.Remove(rc1);

                    ModifiedLinkedShutdownList.Remove(ModifiedSelectedActivity);

                    IsRCReversed = true;
                }
                else
                {
                    if (ModifiedSelectedActivity.LsdReason == "Rerouted to ByPass" || ModifiedSelectedActivity.LsdReason == "Rerouted to USOSSP")
                    {
                        int parentUnitId;
                        if (ModifiedSelectedActivity.LsdReason == "Rerouted to ByPass")
                            parentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId;
                        else
                            parentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId;
                        RadialSwitch radialSwitch = null;
                        foreach (RadialSwitch radial in ServiceLocator.Get<AppointmentVM>().RadialSwitchList)
                        {
                            if (radial.UnitId == ModifiedSelectedActivity.UnitID && radial.ParentUnitId == parentUnitId && radial.StartDate == ModifiedSelectedActivity.Start && radial.EndDate == ModifiedSelectedActivity.End)
                                radialSwitch = radial;
                        }
                        if (radialSwitch != null)
                            ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Remove(radialSwitch);
                        else
                        {
                            #region If we revert db radial switch we have to remove it from db radial list
                            RadialSwitch dbRadialSwitch = null;
                            foreach (RadialSwitch radial in ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB)
                            {
                                if (radial.UnitId == ModifiedSelectedActivity.UnitID && radial.ParentUnitId == parentUnitId && radial.StartDate == ModifiedSelectedActivity.Start && radial.EndDate == ModifiedSelectedActivity.End)
                                    dbRadialSwitch = radial;
                            }
                            #endregion

                            if (dbRadialSwitch != null)
                                ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB.Remove(dbRadialSwitch);

                            radialSwitch = new RadialSwitch();
                            radialSwitch.IsRevert = true;
                            radialSwitch.ScenarioId = ServiceLocator.Get<ImportVM>().CurrentScenarioId;
                            radialSwitch.UnitId = ModifiedSelectedActivity.UnitID;
                            if (ModifiedSelectedActivity.LsdReason == "Rerouted to ByPass")
                                radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId;
                            else
                                radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId;
                            radialSwitch.StartDate = ModifiedSelectedActivity.Start;
                            radialSwitch.EndDate = ModifiedSelectedActivity.End;
                            ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Add(radialSwitch);
                        }

                        RemoveRadialSwitchLSD(ModifiedSelectedActivity);

                    }

                    /*if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_RADIAL || SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER)
                        FindParentUnit(ModifiedSelectedActivity);
                    else
                    {
                        Unit unit = UnitList.Where(s => s.UnitID == ModifiedSelectedActivity.UnitID).FirstOrDefault();
                        if (unit != null)
                            UpperLevelUnit = UnitList.Where(p => p.UnitID == unit.ParentUnitID).FirstOrDefault();
                    }
                    if (UpperLevelUnit != null && (UpperLevelUnit != SelectedLSDLocation))
                    {
                        if (ModifiedSelectedActivity.UnitType == FIFPConstants.UNITTYPE_TOWER)
                        {
                            GetTowerChildUnits(ModifiedSelectedActivity.UnitID);
                        }
                        else
                        {
                            GetChildUnitNameList(UnitList.Where(p => p.ParentUnitID == ModifiedSelectedActivity.UnitID).ToList(), true);
                        }
                        //List<int> unitIds = GetTowerChildUnits(ModifiedSelectedActivity.UnitID);//Test Later
                        SelectedActivity.LsdPlans.Where(p => childUnits.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = true; });
                    }
                    else*/
                    {
                        SelectedActivity.IsDefaultUnitShutdown = false;//For selected activity we no need to set isLinkedShutdown=false just set IsOpen = true
                        //SelectedActivity.UnitStatus = "C";

                        ActivityType activityCode = ServiceLocator.Get<ImportVM>().ActivityCodeDivisionList.Where(s => s.Name == SelectedActivity.ActivityCode && s.ActivityStatus != "Open").FirstOrDefault();
                        if (activityCode != null && SelectedActivity.UnitStatus == "Open")
                        {
                            SelectedActivity.UnitStatus = activityCode.ActivityStatus;
                            SelectedActivity.ActivityId = activityCode.Id;
                        }
                        if (ModifiedSelectedActivity.UnitType == FIFPConstants.UNITTYPE_TOWER)
                        {
                            GetTowerChildUnits(ModifiedSelectedActivity.UnitID);
                        }
                        else
                        {
                            GetChildUnitNameList(UnitList.Where(p => p.ParentUnitID == ModifiedSelectedActivity.UnitID).ToList(), true);
                        }
                        //List<int> unitIds = GetTowerChildUnits(ModifiedSelectedActivity.UnitID);//Test Later
                        SelectedActivity.LsdPlans.Where(p => childUnits.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = true; });
                        childUnits = new List<int>();
                    }

                    List<int> lsdIds = ModifiedLinkedShutdownList.Where(f => f.UnitID != ModifiedSelectedActivity.UnitID).Select(p => p.UnitID).ToList<int>();
                    string Ids = string.Join(",", lsdIds);
                    SelectedActivity.LSDDeletedIds = Ids;
                    SelectedActivity.IsModified = SelectedActivity.IsModified == 1 ? 1 : 0;

                    ModifiedSelectedActivity.LsdReason = string.Empty;
                    IsLSDRevertEnabled = false;
                    ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(ModifiedLinkedShutdownList.Where(f => f.UnitID != ModifiedSelectedActivity.UnitID));

                    ModifiedSelectedActivity.IsLinkedShutdownPlan = true;
                    ModifiedSelectedActivity.LsdReason = string.Empty;
                    BindScheduleView();
                }
            }
        }

        private void RemoveRadialSwitchLSD(FIFPAppointment ModifiedSelectedActivity)
        {
            List<FIFPAppointment> Plans = new List<FIFPAppointment>();
            if (ModifiedSelectedActivity.LsdReason == "Rerouted to ByPass")//OCCP
            {
                Plans = ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId).ToList<FIFPAppointment>();
            }
            else
            {
                Plans = ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.USOSSPUnitId).ToList<FIFPAppointment>();
            }

            foreach (FIFPAppointment plan in Plans)
            {
                bool overlap = !(plan.End < ModifiedSelectedActivity.Start || plan.Start > ModifiedSelectedActivity.End);
                if (overlap)
                {
                    childUnitList.Add(ModifiedSelectedActivity.UnitID);
                    GetChildUnitNameList(UnitList.Where(s => s.ParentUnitID == ModifiedSelectedActivity.UnitID).ToList<Unit>());
                    plan.LsdPlans.RemoveAll(s => childUnitList.Any(p => p.Equals(s.UnitID)) && s.IsRadialSwitch == true);
                }
                if (ModifiedSelectedActivity.LsdReason == "Rerouted to USOSSP")//Remove the bypass radial from USOSSP radial list
                {
                    if (ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Contains(ModifiedSelectedActivity.UnitID))
                        ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Remove(ModifiedSelectedActivity.UnitID);
                }
            }
        }
        private List<int> childUnitList = new List<int>();
        private void GetChildUnitNameList(List<Unit> lstUnits)
        {
            foreach (Unit unit in lstUnits)
            {
                childUnitList.Add(unit.UnitID);
                GetChildUnitNameList(UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList());
            }
        }

        private void BindScheduleView()
        {
            SelectedClosedString = FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS;//Make closed string drop down selected values to allstring by default
            //Load Timeline View
            List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();
            foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
            {
                lsdPlans.Add(appointment);


                if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PIPELINE && SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_MOL)
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || (l.UnitType == FIFPConstants.UNITTYPE_PIPELINE && l.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL) && l.IsLinkedShutdownPlan == true));
                else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PLATFORM && SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM)
                {
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => (l.UnitName == FIFPConstants.PLATFORM_ERP_UNIT || l.UnitName == FIFPConstants.PLATFORM_NRP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || l.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT) && l.IsLinkedShutdownPlan == true));
                    appointment.FilteredLsdPlans.AddRange(appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_RADIAL && s.IsLinkedShutdownPlan == true));
                    //appointment.FilteredLsdPlans.AddRange(appointment.LsdPlans.Where(s => OccpRadialUnitIds.Any(l => l.Equals(s.UnitID) && s.IsLinkedShutdownPlan == true)));
                }
                else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PIPELINE && SelectedLSDLocation.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_RADIAL && l.IsLinkedShutdownPlan == true));
                else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PLATFORM && (SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CSP_UNIT || SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CSP_1_UNIT))
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_SEPERATOR && l.IsLinkedShutdownPlan == true));
                else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PLATFORM && SelectedLSDLocation.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR || l.UnitType == FIFPConstants.UNITTYPE_TOWER) && l.IsLinkedShutdownPlan == true));
                else if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => (l.UnitType == FIFPConstants.UNITTYPE_RADIAL || l.UnitType == FIFPConstants.UNITTYPE_MODULE) && l.IsLinkedShutdownPlan == true));
                else if (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER && appointment.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                {
                    if (appointment.FilteredLsdPlans.Count == 0)
                        appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                }
                else
                    appointment.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(appointment.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));

                lsdPlans.AddRange(appointment.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));
            }

            if (lsdPlans != null && lsdPlans.Count > 0)
            {
                //if (activity.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || activity.UnitName == FIFPConstants.TOWER_UT_22A || activity.UnitName == FIFPConstants.TOWER_UT_12A || activity.UnitName == FIFPConstants.TOWER_UT_40)
                if (!string.IsNullOrEmpty(SelectedClosedString) && SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER && (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_22A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_12A || SelectedLSDLocation.UnitName == FIFPConstants.TOWER_UT_40))
                {
                    lsdPlans.ForEach(s => { s.SelectedString = SelectedClosedString; });
                }
                else
                {
                    foreach (FIFPAppointment towerAppointment in lsdPlans)
                    {
                        if (towerAppointment.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || towerAppointment.UnitName == FIFPConstants.TOWER_UT_22A || towerAppointment.UnitName == FIFPConstants.TOWER_UT_12A || towerAppointment.UnitName == FIFPConstants.TOWER_UT_40)
                            towerAppointment.SelectedString = SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_OIL ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS : SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_WATER ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS : SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_GAS ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_GASSTRINGS : FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS;
                        else
                            towerAppointment.SelectedString = (towerAppointment.FluidType == FIFPConstants.FLUIDTYPE_OIL) ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS : (towerAppointment.FluidType == FIFPConstants.FLUIDTYPE_WATER) ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS : (towerAppointment.FluidType == FIFPConstants.FLUIDTYPE_GAS) ? FIFPConstants.SHUTDOWN_CLOSEDSTRING_GASSTRINGS : string.Empty;
                    }
                }
            }

            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lsdPlans);//we have to update the plans with this list for retaining
            LoadTimelineView(lsdPlans);
        }

        private void FindParentUnit(FIFPAppointment appointment)
        {
            Unit unit = UnitList.Where(s => s.UnitID == appointment.UnitID).FirstOrDefault();
            GetUnitNameList(unit);
        }

        List<int> childUnits = new List<int>();
        private void GetTowerChildUnits(int unitId)
        {
            Unit towerUnit = UnitList.Where(p => p.UnitID == unitId).FirstOrDefault();
            if (towerUnit != null)
            {
                Unit pipelineUnit = UnitList.Where(p => p.UnitID == towerUnit.ParentUnitID).FirstOrDefault();
                childUnits.Add(pipelineUnit.UnitID);
                List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId).ToList<Unit>();
                lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                childUnits.AddRange(lstChildUnits.Select(s => s.UnitID).ToList<int>());
            }
        }

        #region Get ChildUnitList

        private void GetChildUnitNameList(List<Unit> lstUnits, bool bInitial)
        {
            if (bInitial) { bInitial = false; }
            else
            {
                foreach (Unit unit in lstUnits)
                    childUnits.Add(unit.UnitID);
            }
            foreach (Unit unit in lstUnits)
            {
                GetChildUnitNameList(UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList(), bInitial);
            }
        }
        #endregion

        private void GetUnitNameList(Unit unit)
        {
            Unit childUnit = UnitList.Where(p => p.UnitID == unit.ParentUnitID).FirstOrDefault();
            if (childUnit.UnitType != FIFPConstants.UNITTYPE_TOWER && childUnit.UnitType != FIFPConstants.UNITTYPE_RADIAL)
                GetUnitNameList(childUnit);
            else
                UpperLevelUnit = childUnit;
        }

        //private List<int> GetTowerChildUnits(int unitId)
        //{
        //    List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId).ToList<Unit>();
        //    lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
        //    return lstChildUnits.Select(s => s.UnitID).ToList<int>();
        //}

        private List<int> GetTowerChildUnitsExceptPipeline(int unitId)
        {
            List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId && s.UnitType != FIFPConstants.UNITTYPE_PIPELINE).ToList<Unit>();
            lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
            return lstChildUnits.Select(s => s.UnitID).ToList<int>();
        }

        private List<int> GetTowerChildUnitsRIGActivities(int unitId)
        {
            List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId && s.UnitType != FIFPConstants.UNITTYPE_PIPELINE).ToList<Unit>();
            lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
            return lstChildUnits.Select(s => s.UnitID).ToList<int>();
        }

        private void ShowPopup(string title, string message)
        {
            Warning warningWindow = new Warning();
            warningWindow.CancelButton.Visibility = Visibility.Collapsed;
            warningWindow.Title = string.Format(title);
            warningWindow.lblMessage.Text = string.Format(message);
            warningWindow.lblMessage.Visibility = Visibility.Visible;
            warningWindow.Show();
            warningWindow.OKButton.Click += (o, e1) =>
            {
                warningWindow.lblMessage.Visibility = Visibility.Collapsed;
            };
        }
        #endregion

        #region Bypass to MOL
        private void BypassToMOL(Button btnBypass)
        {
            if (SelectedActivity != null)
            {
                SelectedActivity.IsBypassMOL = true;
                SelectedActivity.IsModified = SelectedActivity.IsModified == 1 ? 1 : 0;
            }
        }
        #endregion

        #region Validation
        protected void NotifyPropertyChanged(Expression<Func<object>> propertyExpression)
        {
            if (propertyExpression == null)
                throw new ArgumentNullException(FIFPConstants.propertyExpression);

            var propertyName = GetPropertyName(propertyExpression);
            OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            Validate(propertyName);
            OnNotifyPropertyChanged();
        }

        protected virtual void OnNotifyPropertyChanged() { }

        private string GetPropertyName(Expression<Func<object>> propertyExpression)
        {
            var unaryExpression = propertyExpression.Body as UnaryExpression;
            var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand;

            var propertyName = memberExpression.Member.Name;

            return propertyName;
        }


        private void NotifyErrorsChanged(string propertyName)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        protected void Validate(string propertyName)
        {
            var value = GetPropertyValue(propertyName);
            RemoveErrorsForProperty(propertyName);
            Validator.TryValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName }, _validationResults);
            NotifyErrorsChanged(propertyName);
        }

        protected void Validate()
        {
            _validationResults.Clear();
            Validator.TryValidateObject(this, new ValidationContext(this, null, null), _validationResults, true);

            foreach (var result in _validationResults)
                NotifyErrorsChanged(result.MemberNames.First());

        }

        private object GetPropertyValue(string propertyName)
        {
            var type = this.GetType();

            var propertyInfo = type.GetProperty(propertyName);

            if (propertyInfo == null)
            {
                throw new ArgumentException(string.Format(FIFPConstants.Couldntfindanyproperty, propertyName, type));
            }

            return propertyInfo.GetValue(this, null);
        }

        private void RemoveErrorsForProperty(string propertyName)
        {
            var validationResults = _validationResults.Where(result => result.MemberNames.Contains(propertyName)).ToList();

            foreach (var result in validationResults)
                _validationResults.Remove(result);
        }

        public IEnumerable GetErrors(string propertyName)
        {
            return _validationResults.Where(result => result.MemberNames.Contains(propertyName));
        }

        public bool HasErrors
        {
            get { return _validationResults.Any(); }
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        //public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}
